unit xView;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Grids, ComCtrls, ZConnection, ZAbstractTable, ZDataset, DB,
  ZAbstractRODataset, ZAbstractDataset, setting,fedit,frmtanda,TPS_TambahN,DaftarkanTPS
  ,TambahPemilih,ComObj,ActiveX, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
  cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls,
  cxGridCustomView, cxGridCustomTableView, cxGridTableView,
  cxGridDBTableView, cxGrid, ftambah, ColorButton, JvThread,
  JvThreadDialog, JvComponentBase, Menus, Grids_ts, TSGrid, TSDBGrid,
  DBGrids, ADODB, DBTables, frxpngimage, cxGridExportLink, ExtCtrls, fRTRW;

type
  TPemilih = record
     ID:String;
     NIK:String;
     NKK:String;
     NAMA:String;
     TEMPAT:String;
     TANGGAL:String;
     IBU:String;
     AGAMA:String;
     KAWIN:String;
     KELAMIN:String;
     KELAINAN:String;
     ALAMAT:String;
     KOTA:String;
     KEC:String;
     DESA:String;
     RW:String;
     RT:String;
     DUSUN:String;
     KET:String;
     STATUS:String;
  end;
  TTPemilih = array of TPemilih;
  TPenyimpan = record
     ID:String;
     NAMA:String;
  end;
  TTPenyimpan = array of TPenyimpan;
  TDpt = record
     KODE:String;
     NAMA:String;
  end;
  TTDpt = array of TDpt;
  TTabel = record
     ID:String;
     TABEL:String;
     COUNT:Integer;
  end;
  TTTabel = array of TTabel;
  TGanda = record
     ID1:String;
     ID2:String;
     KET:Integer;
  end;
  TTGanda = array of TGanda;
  TForm_NView = class(TForm)
    GroupBox3: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    cbKabkot: TComboBox;
    cbKec: TComboBox;
    cbDesa: TComboBox;
    btnRefresh: TButton;
    GroupBox1: TGroupBox;
    lblHal: TLabel;
    btnNext: TButton;
    btnPrev: TButton;
    txtHal: TEdit;
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    sgGanda: TStringGrid;
    PageControl2: TPageControl;
    TabSheet3: TTabSheet;
    TabSheet4: TTabSheet;
    TabSheet5: TTabSheet;
    TabSheet6: TTabSheet;
    ZQuery1: TZQuery;
    ZTable2: TZTable;
    ZConnection1: TZConnection;
    ZTable1: TZTable;
    ZQuery2: TZQuery;
    btnBuat4: TButton;
    sgSejarah: TStringGrid;
    cxGrid1DBTableView1: TcxGridDBTableView;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    cxGrid1TableView1: TcxGridTableView;
    cxGrid1TableView1Column1: TcxGridColumn;
    cxGrid1TableView1Column2: TcxGridColumn;
    cxGrid1TableView1Column3: TcxGridColumn;
    cxGrid1TableView1Column4: TcxGridColumn;
    cxGrid1TableView1Column5: TcxGridColumn;
    cxGrid1TableView1Column6: TcxGridColumn;
    cxGrid1TableView1Column7: TcxGridColumn;
    cxGrid1TableView1Column8: TcxGridColumn;
    cxGrid1TableView1Column9: TcxGridColumn;
    cxGrid1TableView1Column10: TcxGridColumn;
    cxGrid1TableView1Column11: TcxGridColumn;
    cxGrid1TableView1Column12: TcxGridColumn;
    cxGrid1TableView1Column13: TcxGridColumn;
    cxGrid1TableView1Column14: TcxGridColumn;
    cxGrid1TableView1Column15: TcxGridColumn;
    cxGrid1TableView1Column16: TcxGridColumn;
    cxGrid1TableView1Column17: TcxGridColumn;
    cxGrid1TableView1Column18: TcxGridColumn;
    Button2: TButton;
    btnDaftar4: TButton;
    Button3: TButton;
    cxGrid1TableView1Column19: TcxGridColumn;
    cxStyleRepository1: TcxStyleRepository;
    cxStyle1: TcxStyle;
    cxStyle2: TcxStyle;
    tambahGb: TGroupBox;
    btnTambah: TButton;
    Button1: TButton;
    DataSource1: TDataSource;
    ZQuery3: TZQuery;
    JvThread1: TJvThread;
    JvThreadSimpleDialog1: TJvThreadSimpleDialog;
    JvThread2: TJvThread;
    JvThreadSimpleDialog2: TJvThreadSimpleDialog;
    JvThread3: TJvThread;
    JvThreadSimpleDialog3: TJvThreadSimpleDialog;
    btnBuat3: TColorButton;
    PopupMenu1: TPopupMenu;
    ambahSatuPemilih1: TMenuItem;
    ambahDuaatauLebihPemilih1: TMenuItem;
    TabSheet7: TTabSheet;
    TabSheet8: TTabSheet;
    dsTop: TDataSource;
    zqTop: TZQuery;
    qTop: TQuery;
    Image1: TImage;
    Image2: TImage;
    ZQuery4: TZQuery;
    Button5: TButton;
    openDlg: TSaveDialog;
    cxGrid2: TcxGrid;
    cxGrid2DBTableView1: TcxGridDBTableView;
    cxGridTableView1: TcxGridTableView;
    cxGridColumn1: TcxGridColumn;
    cxGridColumn2: TcxGridColumn;
    cxGridColumn3: TcxGridColumn;
    cxGridColumn4: TcxGridColumn;
    cxGridColumn5: TcxGridColumn;
    cxGridColumn6: TcxGridColumn;
    cxGridColumn7: TcxGridColumn;
    cxGridColumn8: TcxGridColumn;
    cxGridColumn9: TcxGridColumn;
    cxGridColumn10: TcxGridColumn;
    cxGridColumn11: TcxGridColumn;
    cxGridColumn12: TcxGridColumn;
    cxGridColumn13: TcxGridColumn;
    cxGridColumn14: TcxGridColumn;
    cxGridColumn15: TcxGridColumn;
    cxGridColumn16: TcxGridColumn;
    cxGridColumn17: TcxGridColumn;
    cxGridColumn18: TcxGridColumn;
    cxGridColumn19: TcxGridColumn;
    cxGrid2Level1: TcxGridLevel;
    dsHistory: TDataSource;
    qryHistory: TZQuery;
    threadKembali: TJvThread;
    ThreadDialogKembali: TJvThreadSimpleDialog;
    btnGanda: TButton;
    qryOnce: TZQuery;
    qrySelect: TZQuery;
    qrySelect2: TZQuery;
    dsGanda: TDataSource;
    threadGanda: TJvThread;
    threadDialogGanda: TJvThreadSimpleDialog;
    threadUbahMerah: TJvThread;
    ThreadDialogUbahMerah: TJvThreadSimpleDialog;
    qrySelect3: TZQuery;
    threadPermanen: TJvThread;
    JvThreadSimpleDialog4: TJvThreadSimpleDialog;
    Panel1: TPanel;
    lblfilter: TLabel;
    btnRTRW: TButton;
    btnMerah: TButton;
    Button4: TButton;
    btnEdit: TButton;
    btnHapus: TButton;
    Label4: TLabel;
    lblKet: TLabel;
    lblketmerah: TLabel;
    lblMerah2: TLabel;
    btnDaftar3: TColorButton;
    Panel2: TPanel;
    lblKet2: TLabel;
    Panel3: TPanel;
    btnPermanen: TButton;
    btnKembalikan: TButton;
    Panel4: TPanel;
    btnPrev2: TButton;
    txtHal2: TEdit;
    btnNext2: TButton;
    lblHal2: TLabel;
    btnCacat: TButton;
    threadCacat: TJvThread;
    threadDialogCacat: TJvThreadSimpleDialog;
    procedure btnHapusClick(Sender: TObject);
    procedure btnPrevClick(Sender: TObject);
    procedure btnNextClick(Sender: TObject);
    procedure txtHalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure cbKabkotChange(Sender: TObject);
    procedure cbKecChange(Sender: TObject);
    procedure cbDesaChange(Sender: TObject);
    procedure btnRefreshClick(Sender: TObject);
//    procedure sgUtamaClick(Sender: TObject);
    procedure btnDaftar4Click(Sender: TObject);
    procedure btnTambahClick(Sender: TObject);
    procedure btnEditClick(Sender: TObject);
    procedure PageControl1Change(Sender: TObject);
    procedure PageControl2Change(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure btnBuat4Click(Sender: TObject);
    procedure sgGandaClick(Sender: TObject);
    procedure btnKembalikanClick(Sender: TObject);
    procedure sgSejarahClick(Sender: TObject);
    procedure cxGrid1TableView1CellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure Button1Click(Sender: TObject);
    procedure btnDaftarClick(Sender: TObject);
    procedure cxGrid1TableView1SelectionChanged(
      Sender: TcxCustomGridTableView);
    procedure Button4Click(Sender: TObject);
    procedure cxGrid1DBTableView1CustomDrawCell(
      Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
      AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
    procedure cxGrid1DBTableView1CellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure JvThread1Execute(Sender: TObject; Params: Pointer);
    procedure Button3Click(Sender: TObject);
    procedure JvThread2Execute(Sender: TObject; Params: Pointer);
    procedure JvThread2FinishAll(Sender: TObject);
    procedure JvThread3Execute(Sender: TObject; Params: Pointer);
    procedure JvThread3FinishAll(Sender: TObject);
    procedure ambahSatuPemilih1Click(Sender: TObject);
    procedure ambahDuaatauLebihPemilih1Click(Sender: TObject);
    procedure tsDBGrid2KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure tsDBGrid1ColMoved(Sender: TObject; ToDisplayCol,
      Count: Integer; ByUser: Boolean);
    procedure tsDBGrid1ColResized(Sender: TObject; RowColnr: Integer);
    procedure tsDBGrid1TopLeftChanged(Sender: TObject; OldCol: Integer;
      OldRow: Variant; NewCol: Integer; NewRow: Variant; ByUser: Boolean);
    procedure tsDBGrid2TopLeftChanged(Sender: TObject; OldCol: Integer;
      OldRow: Variant; NewCol: Integer; NewRow: Variant; ByUser: Boolean);
    procedure tsDBGrid1GetDrawInfo(Sender: TObject; DataCol: Integer;
      DataRow: Variant; var DrawInfo: TtsDrawInfo);
    procedure tsDBGrid1ClickCell(Sender: TObject; DataColDown: Integer;
      DataRowDown: Variant; DataColUp: Integer; DataRowUp: Variant;
      DownPos, UpPos: TtsClickPosition);
    procedure DBGrid1ColumnMoved(Sender: TObject; FromIndex,
      ToIndex: Integer);
    procedure DBGrid1CellClick(Column: TColumn);
    procedure cxGrid1DBTableView1DataControllerFilterChanged(
      Sender: TObject);
    procedure cxGrid1DBTableView1SelectionChanged(
      Sender: TcxCustomGridTableView);
    procedure cxGrid1DBTableView1EditKeyUp(Sender: TcxCustomGridTableView;
      AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word;
      Shift: TShiftState);
    procedure Button5Click(Sender: TObject);
    procedure threadKembaliExecute(Sender: TObject; Params: Pointer);
    procedure threadKembaliFinishAll(Sender: TObject);
    procedure cxGrid2DBTableView1CellClick(Sender: TcxCustomGridTableView;
      ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
      AShift: TShiftState; var AHandled: Boolean);
    procedure btnGandaClick(Sender: TObject);
    procedure threadGandaExecute(Sender: TObject; Params: Pointer);
    procedure btnMerahClick(Sender: TObject);
    procedure threadUbahMerahExecute(Sender: TObject; Params: Pointer);
    procedure threadUbahMerahFinishAll(Sender: TObject);
    procedure threadGandaFinishAll(Sender: TObject);
    procedure btnRTRWClick(Sender: TObject);
    procedure btnPermanenClick(Sender: TObject);
    procedure threadPermanenFinishAll(Sender: TObject);
    procedure threadPermanenExecute(Sender: TObject; Params: Pointer);
    procedure btnCacatClick(Sender: TObject);
    procedure threadCacatFinishAll(Sender: TObject);
    procedure threadCacatExecute(Sender: TObject; Params: Pointer);
  private
    procedure FetchDB;
    procedure TampilHalaman(Hal:Integer = 1);
    procedure GetData(Hal: Integer);
    procedure reviewTabel();
    function getDesa(kode: String): String;
    function getIduser(id: String): String;
    function getTabel(id: String): String;
    function getIdsimpan(tabel: String): String;
    function getKabkot(kode: String): String;
    function getKec(kode: String): String;
    function getSimpan(id: String): String;
    procedure AutoSizeCol(Grid: TStringGrid; Column: integer);
    procedure getPage;
    function cariPos(nama:String; nik:String):integer;
    function cekBGanda(id: String): Boolean;
    procedure showGanda(idganda: String);
    procedure FetchDB2(id: Integer);
    procedure TampilHalaman2(id:Integer; Hal: Integer = 1);
    procedure GetData2(id:Integer; Hal: Integer);
    procedure InitFilterGrid;
    function  GetFilter: string;
    function HandleSpec(Asal: String):String;
    procedure SetFilter;

    { Private declarations }
  public
    { Public declarations }
    constructor Create(AOwner: TComponent; kode_login:string;isneedtambah:boolean;kode_proses:integer;user:string);overload;
  end;

var
  pemilih_kembali, ubah_merah, ubah_merah_tabel, ubah_cacat, ubah_cacat_tabel: TstringList;
  FSettingTopLeft: Boolean;
  jadi:boolean;
  Form_NView: TForm_NView;
  fEdit:TForm3;
  fTanda:TForm5;
  tambahntps:TForm_TambahTPS;
  fDaftar: TForm_DaftarkanTPS;
  ftambah:TForm_Ftambah;
  fTambahp: TForm_TambahPemilih;
  sKabkot:String;
  sKec:String;
  sDesa:String;
  skodekab,skodekec:string;
  posutama:integer;
  cRow,crow2:Integer; //currentrow
  dRow,drow2:Integer; //data row
  cHal,chal2:Integer; //current halaman
  jHal,jhal2:Integer; //jumlah halaman
  bHal:Integer; //batas per halaman
  bPemilih,bPemilih2: TTPemilih;
  bPenyimpan:TTPenyimpan;
  bDesa:TTDpt;
  bKec:TTDpt;
  bKabkot:TTDpt;
  bTabel,bTabel2:TTTabel;
  bGanda:TTGanda;
  bIdganda:array of String;
  bGridganda:TTPenyimpan;
  ptable,ptable2:String;
  pid,pid2,tid,tid2:String;
  prosesed:Boolean;
  isreqtambah:boolean;
  gdata:Boolean;
  countthread,count2thread, count3thread:Integer;
  proses_asal:integer;
  username:string;
  totalhapus:integer;
implementation

{$R *.dfm}

constructor TForm_NView.Create(AOwner: TComponent; kode_login: string;isneedtambah:boolean;kode_proses:integer;user:string);
begin
  inherited Create(AOwner);

  if(length(kode_login)>2)then
  begin
    skodekab:=copy(kode_login,1,2);
    skodekec:=kode_login;
  end
  else
  begin                
    skodekab:=kode_login;
    skodekec:='';
  end;
  //skode:=kode_login;

  isreqtambah:=isneedtambah;
  proses_asal:=kode_proses;
  username:=user;
end;

procedure TForm_NView.btnBuat4Click(Sender: TObject);
begin
  if (sdesa<>'') then begin
    tambahntps:=TForm_TambahTPS.Create(Application,sdesa,1);
  end;
end;

function TForm_NView.cariPos(nama:String; nik:String):integer;
var
  i:integer;
begin
  for I:=0 to High(bPemilih) do begin
    if (nama=bpemilih[i].NAMA) and (nik=bPemilih[i].NIK) then
      break;
  end;
  //showmessage(IntToStr(i));
  Result:=i;
end;

procedure TForm_NView.btnDaftar4Click(Sender: TObject);
var
  iduser,nik:String;
  i,j,pt,tots:integer;
  pemilihs: TStringList;
begin
//  showMessage(inttostr(tsDBGrid1.SelectedRows.Count));
  skode:=skodekec;
 // if(tsDBGrid1.SelectedRows= nil) then begin
//  showmessage(skode);
 // end;
  if (cxGrid1DBTableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilihs := Tstringlist.Create;
    with cxGrid1DBTableView1.Controller do begin
        for i:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[i].Values[0];
          pemilihs.Add(iduser);
        end;
    end;
    fDaftar:= TForm_DaftarkanTPS.Create(Application,sdesa,pemilihs,skode);
  end
    else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
end;

procedure TForm_NView.btnEditClick(Sender: TObject);
var ckode:string;
begin
  if (cxGrid1DBTableView1.Controller.SelectedRowCount=1) then begin
    tid:=getIdsimpan(ptable);
//    showmessage(username);
  if(skodekec<>'')then ckode:=skodekec
  else ckode:=skodekab;
    fEdit := TForm3.Create(Application,ptable,pid,tid,false,1,ckode,username);
  end
    else
  ShowMessage('Pilih salah satu pemilih saja');
end;

procedure TForm_NView.btnHapusClick(Sender: TObject);
var
  pos:Integer;
  tots,i:Integer;
  ID,iduser:String;
  tabel:String;
  que:String;
  pemilihs:TStringList;
begin
  //lebih dari satu
  if (cxGrid1DBTableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilihs := Tstringlist.Create;
    with cxGrid1DBTableView1.Controller do begin
        for i:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[i].Values[0];
          pemilihs.Add(iduser);
        end;
    end;
    fTanda := TForm5.Create(Application,ptable,pid,true,tid,1,pemilihs,username);
  end
  else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
  {pos:=StringGrid1.Row;
  //getID
  tabel:=Copy(bPemilih[pos].ID,1,16);
  tots:=Length(bPemilih[pos].ID)-16;
  ID:=Copy(bPemilih[pos].ID,17,tots);
  //get tabel
  //get ID di tabel
  //query
  with ZQuery1 do
    begin
      Active := False;
      que:='DELETE FROM '+tabel+' WHERE ID_USER='+ID;
      SQL.Text := que;
      ExecSQL;
    end;
  //hapus array
  ShowMessage('Pemilih telah dihapus');}

  //hati-hati ganti
  {tid:=getIdsimpan(ptable);
  if (cekBGanda(tid+'-'+pid)) then
    fTanda := TForm5.Create(Application,ptable,pid,true,tid,1,username)
  else
    fTanda := TForm5.Create(Application,ptable,pid,false,tid,1,username)}
end;

procedure TForm_NView.btnKembalikanClick(Sender: TObject);
var
  query,ique,itabel,id_pemilih,iduser:String;
  buttonSelected, idx : Integer;
  pemilihs : tstringList;
begin
//  ShowMessage(ptable2+' '+pid2+' '+tid2);
  //ambil yg diselect
  if (cxGrid2DBTableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilih_kembali := Tstringlist.Create;
    with cxGrid2DBTableView1.Controller do begin
        for idx:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[idx].Values[0];
          pemilih_kembali.Add(iduser);
        end;
    end;
    buttonSelected := MessageDlg('Apakah anda yakin akan mengembalikan data ini?',mtConfirmation , mbOKCancel, 0);
    if buttonSelected = mrOK  then begin
      ThreadKembali.ThreadDialog:=ThreadDialogKembali;
      ThreadKembali.Execute(Self);
    end;
  end
    else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
end;

procedure TForm_NView.btnNextClick(Sender: TObject);
begin
  TampilHalaman(cHal+1);
  txtHal.Text:=IntToStr(cHal);
end;

procedure TForm_NView.btnPrevClick(Sender: TObject);
begin
  TampilHalaman(cHal-1);
  txtHal.Text:=IntToStr(cHal);
end;


procedure TForm_NView.btnRefreshClick(Sender: TObject);
begin
  cxGrid1DBTableView1.DataController.DataModeController.GridMode:=True;
  prosesed:=true;
  FetchDB;
  btnEdit.Enabled:=False;
  btnMerah.Enabled:=false;
  btnTambah.Enabled:=true;
  btnBuat3.Enabled:=true;
  btnDaftar3.Enabled:=true;
  if(sdesa<>'') then begin
    //btnDaftar.Enabled:=true;
    btnDaftar3.Enabled:=true;
  end;
  Button4.Enabled:=true;
  Button1.enabled:=true;
  btnHapus.Enabled:=False;
  Button2.Enabled:=true;
  btnRefresh.Enabled:=true;
  PageControl1.ActivePage:=TabSheet1;
  cxGrid1DBTableView1.DataController.DataModeController.GridMode:=False;
  //reviewTabel;
  //JvThread1.ThreadDialog:=JvThreadSimpleDialog1;
  //JvThread1.Execute(self);
end;

procedure TForm_NView.reviewTabel();
var
  s:String;
  i:integer;
begin
  for i:=0 to cxGrid1DBTableView1.DataController.RowCount-1 do begin
    with cxGrid1DBTableView1.DataController do begin
      if Values[i,8]='S' then
        Values[i,8]:='SUDAH'
      else if Values[i,8]='B' then
        Values[i,8]:='BELUM'
      else
        Values[i,8]:='CERAI';
      //
      Values[i,16]:=0;
      //
      if Values[i,17]<>0 then begin
        with zquery1 do begin
          active:=false;
          sql.clear;
          sql.text:='SELECT NAMA FROM daftar_tps WHERE ID_TPS='+VarToStr(Values[i,17]);
          active:=true;
          first;
          Values[i,17]:=zquery1.fields[0].AsVariant;
        end;
      end;
      //
    end;
  end;
end;

procedure TForm_NView.FetchDB();
begin
  lblHal.Caption:='-';
  gdata:=False;
  //utama
  with cxGrid1DBTableView1.DataController do
  begin
    BeginUpdate;
    try
      while RecordCount > 0 do
        DeleteRecord(0);
    finally
      EndUpdate;
    end;
    RecordCount:=0;
  end;

  JvThread2.ThreadDialog:=JvThreadSimpleDialog2;
  JvThread2.Execute(self);





end;

procedure TForm_NView.TampilHalaman(Hal:Integer = 1);
var
  iter,i:Integer;
  tabel,iduser,tanda,query,tambahan_where:String;
begin
  txtHal.Enabled:=True;
  lblHal.Caption := IntToStr(Hal)+' of '+IntToStr(jHal);
  cHal:=Hal;
  //GetData(Hal);
  cRow:=1;
  SetLength(bGanda,0);
  //
  cxGrid1DBTableView1.DataController.Filter.Clear;
  cxGrid1DBTableView1.ClearItems;

  //JvThread3.ThreadDialog:=JvThreadSimpleDialog3;
  //JvThread3.Execute(self);
  tambahan_where := '';
  if proses_asal = 2 then
    tambahan_where := ' AND STATUS1 <> 1'
  else if proses_asal = 8 then
    tambahan_where := ' AND STATUS1 = 1';
//  showMessage('SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT LAHIR`, a.TANGGAL AS `TANGGAL LAHIR`, a.IBU, a.KAWIN AS `STATUS PERKAWINAN`, a.KELAMIN AS `JENIS KELAMIN`, a.ALAMAT, a.RW, a.RT, b.NAMA AS `DI TPS`, a.GANDA  FROM pemilih_'+sdesa+' a LEFT JOIN daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0"'+tambahan_where+' ORDER BY a.NKK ASC');
  with zquery3 do begin
      active:=false;
      sql.clear;
      sql.text:='SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT_LAHIR`, a.TANGGAL AS `TANGGAL_LAHIR`, a.IBU, a.KAWIN AS `STATUS_PERKAWINAN`, a.KELAMIN AS `JENIS_KELAMIN`, a.ALAMAT, a.RW, a.RT, a.DUSUN, b.NAMA AS `DI_TPS`, a.GANDA,'+' IF(a.CACAT = 1,''Cacat Fisik'',IF(a.CACAT = 2,''Cacat Netra/Buta'',IF(a.CACAT=3,''Cacat Rungu Wicara'',IF(a.CACAT=4,''Cacat Mental/Jiwa'',IF(a.CACAT=5,'+'''Cacat Fisik Mental'',IF(a.CACAT=6,''Cacat Lainnya'','''')))))) as `PEN_CACAT` FROM pemilih_'+sdesa+' a LEFT JOIN'+' daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0"'+tambahan_where+' ORDER BY b.NAMA, a.STATUS1, a.RW,a.RT,a.NKK,a.NIK ASC';
//      sql.text:='SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT LAHIR`, a.TANGGAL AS `TANGGAL LAHIR`, a.IBU, a.KAWIN AS `STATUS PERKAWINAN`, a.KELAMIN AS `JENIS KELAMIN`, a.ALAMAT, a.RW, a.RT, b.NAMA AS `DI TPS`, a.GANDA  FROM pemilih_all'+' a LEFT JOIN'+' daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0"'+tambahan_where+' AND MATCH(a.TABEL) AGAINST('+QuotedStr('pemilih_'+sdesa)+') ORDER BY a.RW,a.RT,a.NKK ASC';
      active:=true;
   end;
   {with zqTop do begin
      active:=false;
      sql.clear;
      sql.text:='SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT_LAHIR`, a.TANGGAL AS `TANGGAL_LAHIR`, a.IBU, a.KAWIN AS `STATUS_PERKAWINAN`, a.KELAMIN AS `JENIS_KELAMIN`, a.ALAMAT, a.RW, a.RT, b.NAMA AS `DI_TPS`, a.GANDA  FROM pemilih_'+sdesa+' a LEFT JOIN'+' daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0"'+tambahan_where+' ORDER BY a.RW,a.RT,a.NKK ASC';
//      sql.text:='SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT LAHIR`, a.TANGGAL AS `TANGGAL LAHIR`, a.IBU, a.KAWIN AS `STATUS PERKAWINAN`, a.KELAMIN AS `JENIS KELAMIN`, a.ALAMAT, a.RW, a.RT, b.NAMA AS `DI TPS`, a.GANDA  FROM pemilih_all'+' a LEFT JOIN'+' daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0"'+tambahan_where+' AND MATCH(a.TABEL) AGAINST('+QuotedStr('pemilih_'+sdesa)+') ORDER BY a.RW,a.RT,a.NKK ASC';
      active:=true;
    end;}
   jadi:=false;

//   qTop:=zqTop;
   //dsTop.DataSet:=zqTop;
   //tsDBGrid1.DataSource:=dsTop;
   {tsDBGrid1.EnableRedraw := false;
   //ADODataSet1.DataSource.DataSet := zquery3;
   DataSource1.DataSet:=zquery3;
//   tsDBGrid1.DataSource:=DataSource1;
   tsDBGrid1.Col[1].Width:=40;
   tsDBGrid1.Col[2].Width:=120;
   tsDBGrid1.Col[3].Width:=120;
   tsDBGrid1.Col[4].Width:=120;
   tsDBGrid1.Col[5].Width:=90;
   tsDBGrid1.Col[7].Width:=120;
   tsDBGrid1.Col[10].Width:=150;
   tsDBGrid1.Col[13].Width:=50;


   {DBGrid1.Columns[0].Width:=40;
   DBGrid1.Columns[1].Width:=120;
   DBGrid1.Columns[2].Width:=120;
   DBGrid1.Columns[3].Width:=120;
   DBGrid1.Columns[4].Width:=90;
   DBGrid1.Columns[6].Width:=120;
   DBGrid1.Columns[9].Width:=150;
   DBGrid1.Columns[12].Width:=50;}
   //TsDBGrid1.Rows := DataSource1.DataSet.RecordCount;
   {tsDBGrid1.EnableRedraw := true;
   tsDBGrid1.Refresh; }
   //tsDBGrid1.RowMoving:=false;
   //tsDBGrid1.RowSelectMode:=rsMulti;
   jadi:=true;
   //initFilterGrid;
   cxGrid1DBTableView1.BeginUpdate;
   cxGrid1DBTableView1.DataController.DataSource:=DataSource1;
   cxGrid1DBTableView1.DataController.CreateAllItems;
   cxGrid1DBTableView1.Columns[0].Width:=40;
   cxGrid1DBTableView1.Columns[1].Width:=105;
   cxGrid1DBTableView1.Columns[2].Width:=105;
   cxGrid1DBTableView1.Columns[3].Width:=120;
   cxGrid1DBTableView1.Columns[4].Width:=90;
   cxGrid1DBTableView1.Columns[6].Width:=120;
   cxGrid1DBTableView1.Columns[9].Width:=150;
   cxGrid1DBTableView1.Columns[12].Width:=150;
   cxGrid1DBTableView1.Columns[14].Width:=50;
   cxGrid1DBTableView1.EndUpdate;
   //tsDBGrid1.visible:=false;
  // showMessage(cxGrid1DBTableView1.Columns[0].Name);

    //
    JvThread1.ThreadDialog:=JvThreadSimpleDialog1;
    JvThread1.Execute(self);


    {with zquery1 do begin
      active:=false;
      sql.clear;
      sql.text:='SELECT * FROM pemilih_'+sdesa+' WHERE STATUS2="0" ORDER BY NKK ASC';
      active:=true;
      first;
    end;
    while not zquery1.Eof do begin
      tabel:=getIdsimpan('pemilih_'+sdesa);
      iduser:=zquery1.fieldbyname('ID_USER').AsString;
      with ZQuery2 do begin
        Active:=false;
        sql.Clear;
        query:='SELECT * FROM data_ganda WHERE ID_USER1="'+tabel+'-'+iduser+'"';
        sql.Text:=query;
        Active:=true;
        First;
        if (FieldByName('ID_USER1').AsString<>'') then begin
          while (not Eof) do begin
            SetLength(bGanda,(Length(bGanda)+1));
            bGanda[Length(bGanda)-1].ID1:=FieldByName('ID_USER1').AsString;
            bGanda[Length(bGanda)-1].ID2:=FieldByName('ID_USER2').AsString;
            bGanda[Length(bGanda)-1].KET:=FieldByName('KETERANGAN').AsInteger;
            Next;
          end;
        end;
      //
        Active:=false;
        sql.Clear;
        query:='SELECT * FROM data_ganda WHERE ID_USER2="'+tabel+'-'+iduser+'"';
        sql.Text:=query;
        Active:=true;
        First;
        if (FieldByName('ID_USER2').AsString<>'') then begin
          while (not Eof) do begin
            SetLength(bGanda,(Length(bGanda)+1));
            bGanda[Length(bGanda)-1].ID1:=FieldByName('ID_USER2').AsString;
            bGanda[Length(bGanda)-1].ID2:=FieldByName('ID_USER1').AsString;
            bGanda[Length(bGanda)-1].KET:=FieldByName('KETERANGAN').AsInteger;
            Next;
          end;
        end;
      end;
      ZQuery1.Next;
    end;}
end;

procedure TForm_NView.GetData(Hal:Integer);
var
  query:String;
  kKota:String;
  kKec:String;
  kDesa:String;
  tabel:TTabel;
  tblName,idsimpan,iduser,idganda:String;
  i:Integer;
  vRow,ujung,awal:Integer;
begin
  dRow:=1;
  vRow:=1;
  //cek
  ujung:=Hal*bHal;
  i:=0;
  {if (jHal>1) then begin
    for I := 0 to (Length(bTabel)) - 1 do begin
      if (ujung<=bTabel[i].COUNT) then
        break;
    end;
    if (i>0) then begin
      ujung:=ujung-btabel[i-1].COUNT;
      if (ujung<bHal) then begin
        Dec(i);
        awal:=bTabel[i].COUNT-(bHal-ujung);
      end else
        awal:=ujung-bHal;
    end
    else begin
      awal:=ujung-bHal;
    end;
  end
    else
  begin
    awal:=0;
    ujung:=bhal;
  end;}
  //showmessage(IntToStr(length(btabel)));
  tblName:=btabel[i].TABEL;
  idsimpan:=btabel[i].ID;
  ZQuery1.Active := False;
  query:= 'SELECT * FROM '+tblName;
  query:=query+' WHERE STATUS2="0"';
  query:=query+' ORDER BY NKK ASC';
  ZQuery1.SQL.Text := query;
  ZQuery1.Active := True;
  ZQuery1.First;  //tabel simpan
  kKota:=Copy(tblName,9,2);
  kKota:=getKabkot(kKota);
  kKec:=Copy(tblName,9,5);
  kKec:=getKec(kKec);
  kDesa:=Copy(tblName,9,8);
  kDesa:=getDesa(kDesa);
  dRow:=dRow+ZQuery1.RecordCount;
  SetLength(bPemilih,dRow);
  while (not ZQuery1.Eof) do begin
    bPemilih[vRow].ID :=ZQuery1.Fields[0].AsString;
    bPemilih[vRow].NIK:=ZQuery1.Fields[1].AsString;
    bPemilih[vRow].NKK:=ZQuery1.Fields[2].AsString;
    bPemilih[vRow].NAMA:=ZQuery1.Fields[3].AsString;
    bPemilih[vRow].TEMPAT:=ZQuery1.Fields[4].AsString;
    bPemilih[vRow].TANGGAL:=ZQuery1.Fields[5].AsString;
    bPemilih[vRow].IBU:=ZQuery1.Fields[6].AsString;
    bPemilih[vRow].AGAMA:=ZQuery1.Fields[7].AsString;
    bPemilih[vRow].KAWIN:=ZQuery1.Fields[8].AsString;
    bPemilih[vRow].KELAMIN:=ZQuery1.Fields[9].AsString;
    bPemilih[vRow].KELAINAN:=ZQuery1.Fields[10].AsString;
    bPemilih[vRow].ALAMAT:=ZQuery1.Fields[11].AsString;
    bPemilih[vRow].KOTA:=kKota;
    bPemilih[vRow].KEC:=kKec;
    bPemilih[vRow].DESA:=kDesa;
    bPemilih[vRow].RW:=ZQuery1.Fields[12].AsString;
    bPemilih[vRow].RT:=ZQuery1.Fields[13].AsString;
    bPemilih[vRow].DUSUN:=ZQuery1.Fields[14].AsString;
    bPemilih[vRow].KET:=ZQuery1.fieldbyname('TPS').AsString;
    bPemilih[vRow].STATUS:=ZQuery1.fieldbyname('STATUS3').AsString;
    Inc(vrow);
    ZQuery1.Next;
  end;
end;

procedure TForm_NView.AutoSizeCol(Grid: TStringGrid; Column: integer);
var
  i, W, WMax: integer;
begin
  WMax := 0;
  for i := 0 to (Grid.RowCount - 1) do begin
    W := Grid.Canvas.TextWidth(Grid.Cells[Column, i]);
    if W > WMax then
      WMax := W;
  end;
  Grid.ColWidths[Column] := WMax + 5;
end;

function TForm_NView.getKec(kode:String):String;
var
  I:integer;
begin
  for I := 0 to Length(bKec) - 1 do begin
    if (bKec[i].KODE=kode) then
      break;
  end;
    Result:=bKec[i].NAMA;
end;

function TForm_NView.getKabkot(kode:String):String;
var
  I:integer;
begin
  for I := 0 to Length(bKabkot) - 1 do begin
    if (bKabkot[i].KODE=kode) then
      break;
  end;
    Result:=bKabkot[i].NAMA;
end;

function TForm_NView.getIdsimpan(tabel:String):String;
var
  I:integer;
  res:String;
begin
  res:='';
  for I := 0 to Length(bPenyimpan) - 1 do begin
    if (bPenyimpan[i].NAMA=tabel) then begin
      res:=bPenyimpan[i].ID;
      break;
    end;
  end;
    Result:=res;
end;

function TForm_NView.getSimpan(id:String):String;
var
  I:integer;
  res:String;
begin
  res:='';
  for I := 0 to Length(bPenyimpan) - 1 do begin
    if (bPenyimpan[i].ID=id) then begin
      res:=bPenyimpan[i].NAMA;
      break;
    end;
  end;
    Result:=res;
end;

function TForm_NView.getTabel(id:String):String;
begin
  Result:=Copy(id,1,16);
end;

function TForm_NView.getIduser(id:String):String;
begin
  Result:=Copy(id,17,(Length(id)-16));
end;

function TForm_NView.getDesa(kode:String):String;
var
  I:integer;
begin
  for I := 0 to Length(bDesa) - 1 do begin
    if (bDesa[i].KODE=kode) then
      break;
  end;
    Result:=bDesa[i].NAMA;
end;

procedure TForm_NView.btnTambahClick(Sender: TObject);

begin
  fTambahp:= TForm_TambahPemilih.Create(Application,sdesa,proses_asal,username);
    tambahGb.Visible:=false;
end;

procedure TForm_NView.cbKabkotChange(Sender: TObject);
var
  pilihan:String;
begin
  btnBuat3.Enabled:=false;
  btnDaftar3.Enabled:=false;
  if (cbKabkot.ItemIndex > 0) then
  begin
    pilihan := cbKabkot.Items[cbKabkot.ItemIndex];
    with ZTable1 do
      begin
        Active := False;
        TableName := 'kabkot';
        Filter := 'TAMPIL = '+QuotedStr(pilihan);
        Filtered := True;
        Active := True;
        First;
        sKabkot := FieldByName('KODE').AsString;
        //cb2
        Active := False;
        TableName := 'kecamatan';
        Filter := 'KODE_KABKOT = '+QuotedStr(sKabkot);
        Filtered := True;
        Active := True;
        First;
      end;
    cbkec.Clear;
    cbDesa.Clear;
    cbkec.Items.Add('');
    while (not ZTable1.Eof) do
      begin
        cbkec.Items.Add(ZTable1.FieldByName('TAMPIL').AsString);
        ZTable1.Next;
      end;
  end
    else
  begin
    sKabkot:='';
    cbkec.Clear;
    cbDesa.Clear;
  end;
  sKec:='';
  sDesa:='';
  btnTambah.Enabled:=False;
  btnEdit.Enabled:=False;
  btnDaftar3.Enabled:=false;
  btnHapus.Enabled:=False;
  btnBuat3.Enabled:=false;
  btnRefresh.Enabled:=false;
  Button2.Enabled:=false;
  Button1.enabled:=false;
end;

procedure TForm_NView.cbKecChange(Sender: TObject);
var
  pilihan:String;
begin
  btnBuat3.Enabled:=false;
  btnDaftar3.Enabled:=false;
  if (cbKec.ItemIndex > 0) then
  begin
    btnGanda.Enabled:=true;
    btnMerah.Enabled:=true;
    
    pilihan := cbKec.Items[cbKec.ItemIndex];
    ZTable1.Active := False;
    ZTable1.TableName := 'kecamatan';
    ZTable1.Filter := 'TAMPIL = '+QuotedStr(pilihan)+' AND KODE_KABKOT = '+QuotedStr(sKabkot);
    ZTable1.Filtered := True;
    ZTable1.Active := True;
    ZTable1.First;
    sKec := ZTable1.FieldByName('KODE_KECAMATAN').AsString;
    //cb3
    ZTable1.Active := False;
    ZTable1.TableName := 'desa';
    ZTable1.Filter := 'KODE_KECAMATAN = '+QuotedStr(sKec);
    ZTable1.Filtered := True;
    ZTable1.Active := True;
    ZTable1.First;
    cbdesa.Clear;
    cbdesa.Items.Add('');
    while (not ZTable1.Eof) do
      begin
        cbdesa.Items.Add(ZTable1.FieldByName('TAMPIL').AsString);
        ZTable1.Next;
      end;
  end
    else
  begin
    btnGanda.Enabled:=false;
    btnMerah.Enabled:=false;
    sKec:='';
    cbdesa.Clear;
  end;
  sDesa:='';
  btnTambah.Enabled:=False;
  btnEdit.Enabled:=False;
  btnDaftar3.Enabled:=false;
  btnHapus.Enabled:=False;
  btnBuat3.Enabled:=false;
  btnRefresh.Enabled:=false;
  Button2.Enabled:=false;
  Button1.enabled:=false;
end;

procedure TForm_NView.FormClose(Sender: TObject; var Action: TCloseAction);
var
  i:integer;
begin
  SetLength(bPemilih,0);
  SetLength(bPemilih2,0);
  SetLength(bTabel,0);
  SetLength(bTabel2,0);
  SetLength(bGanda,0);
  SetLength(bIdganda,0);
  SetLength(bGridganda,0);
  //hapus history
      for i := 1 to sgGanda.RowCount - 1
        do sgGanda.Rows[i].Clear;
      sgGanda.RowCount:=2;
          for i := 1 to sgSejarah.RowCount - 1
        do sgSejarah.Rows[i].Clear;
      sgSejarah.RowCount:=2;
  Action := caFree;
end;



procedure TForm_NView.FormCreate(Sender: TObject);
var
  I: Integer;
  setting:TSetting_Form;
  pilihan:string;
  p, Grid, RowIndexes : OleVariant;
begin
  //for i := 0 to cxGrid1.ColCount - 1 do
    //AutoSizeCol(cxGrid1, i);
  //for i := 0 to sgganda.ColCount - 1 do
  //  AutoSizeCol(sgGanda, i);
  //cxGrid1.
  if(isreqtambah<>true)then
  begin
    Button4.Visible:=false;
    Button1.Visible:=false;
    btnTambah.Visible:=false;
  end;
  //
  setting:=TSetting_Form.Create;
  ZConnection1.HostName:=setting.host;
  ZConnection1.Protocol:=setting.protocol;
  ZConnection1.Database:=setting.database;
  ZConnection1.User:=setting.user;
  ZConnection1.Password:=setting.password;
  ZConnection1.Connected:=true;
  ztable1.Connection:=ZConnection1;
  ZQuery1.Connection:=ZConnection1;
  ztable2.Connection:=ZConnection1;
  ZQuery2.Connection:=ZConnection1;
  ZQuery3.Connection:=ZConnection1;
  zqTop.Connection:=Zconnection1;
  ZConnection1.LoginPrompt:=False;
  ZConnection1.Connected := True;
  //Komponen
  sKabkot:='';
  sKec:='';
  sDesa:='';
  cRow:=2;  //wadah row
  dRow:=1;  //menyimpan banyaknya data
  bHal:=25;  //pemilih per halaman
  lblHal.Caption:= '-';
  btnRefresh.Enabled:=False;
  txtHal.Enabled:=False;
  btnPrev.Enabled:=False;
  btnNext.Enabled:=False;
  txtHal2.Enabled:=false;
  btnNext2.Enabled:=false;
  btnPrev2.Enabled:=false;
  btnTambah.Enabled:=False;
  btnEdit.Enabled:=False;
  btnHapus.Enabled:=False;
  btnBuat3.Enabled:=false;
  btnDaftar3.Enabled:=False;
  Button1.enabled:=false;
  lblKet.Caption:='';
  lblKetmerah.Caption:='';
  lblMerah2.Caption:='';
  lblKet2.Caption:='';
  //Grid
  {
  cxGrid1TableView1Column1.Caption:='NO';
  cxGrid1TableView1Column2.Caption:='NIK';
  cxGrid1TableView1Column3.Caption:='NKK';
  cxGrid1TableView1Column4.Caption:='Nama';
  cxGrid1TableView1Column5.Caption:='Tempat Lahir';
  cxGrid1TableView1Column6.Caption:='Tanggal Lahir';
  cxGrid1TableView1Column7.Caption:='Nama Ibu';
  cxGrid1TableView1Column8.Caption:='Perkawinan';
  cxGrid1TableView1Column9.Caption:='Jenis Kelamin';
  cxGrid1TableView1Column10.Caption:='Alamat';
  cxGrid1TableView1Column11.Caption:='Kota';
  cxGrid1TableView1Column12.Caption:='Kecamatan';
  cxGrid1TableView1Column13.Caption:='Desa';
  cxGrid1TableView1Column14.Caption:='RW';
  cxGrid1TableView1Column15.Caption:='RT';
  cxGrid1TableView1Column16.Caption:='Dusun';
  cxGrid1TableView1Column17.Caption:='TPS';
  cxGrid1TableView1Column18.Caption:='Ganda';
  cxGrid1TableView1Column19.Caption:='Status';
  }
  //
  sgGanda.ColCount:=19;
  sgGanda.Cells[0,0]:='NO';
  sgGanda.Cells[1,0]:='NIK';
  sgGanda.Cells[2,0]:='NKK';
  sgGanda.Cells[3,0]:='Nama';
  sgGanda.Cells[4,0]:='Tempat Lahir';
  sgGanda.Cells[5,0]:='Tanggal Lahir';
  sgGanda.Cells[6,0]:='Nama Ibu';
  sgGanda.Cells[7,0]:='Perkawinan';
  sgGanda.Cells[8,0]:='Jenis Kelamin';
  sgGanda.Cells[9,0]:='Alamat';
  sgGanda.Cells[10,0]:='Kota/Kab';
  sgGanda.Cells[11,0]:='Kecamatan';
  sgGanda.Cells[12,0]:='Desa/Kel';
  sgGanda.Cells[13,0]:='RW';
  sgGanda.Cells[14,0]:='RT';
  sgGanda.RowCount:=cRow;
  //
  sgSejarah.ColCount:=20;
  sgSejarah.Cells[0,0]:='NO';
  sgSejarah.Cells[1,0]:='NIK';
  sgSejarah.Cells[2,0]:='NKK';
  sgSejarah.Cells[3,0]:='Nama';
  sgSejarah.Cells[4,0]:='Tempat Lahir';
  sgSejarah.Cells[5,0]:='Tanggal Lahir';
  sgSejarah.Cells[6,0]:='Nama Ibu';
  sgSejarah.Cells[7,0]:='Agama';
  sgSejarah.Cells[8,0]:='Perkawinan';
  sgSejarah.Cells[9,0]:='Jenis Kelamin';
  sgSejarah.Cells[10,0]:='Kelainan';
  sgSejarah.Cells[11,0]:='Alamat';
  sgSejarah.Cells[12,0]:='Kota/Kab';
  sgSejarah.Cells[13,0]:='Kecamatan';
  sgSejarah.Cells[14,0]:='Desa/Kel';
  sgSejarah.Cells[15,0]:='RW';
  sgSejarah.Cells[16,0]:='RT';
  sgSejarah.Cells[17,0]:='Dusun';
  sgSejarah.Cells[18,0]:='Ket';
  sgSejarah.Cells[19,0]:='Status';
  sgSejarah.RowCount:=cRow;
  //TABEL-TABEL
  with ZTable1 do begin
    Active:=False;
    TableName:='penyimpan';
    Active:=True;
    SetLength(bPenyimpan,RecordCount);
    I:=0;
    while (not Eof) do begin
      bPenyimpan[I].ID:=FieldByName('ID').AsString;
      bPenyimpan[I].NAMA:=FieldByName('NAMA').AsString;
      Inc(I);
      Next;
    end;
  end;

  //desa
  with ZTable1 do begin
    Active:=False;
    TableName:='desa';
    Active:=True;
    SetLength(bDesa,RecordCount);
    I:=0;
    while (not Eof) do begin
      bDesa[I].KODE:=FieldByName('KODE_DESA').AsString;
      bDesa[I].NAMA:=FieldByName('TAMPIL').AsString;
      Inc(I);
      Next;
    end;
  end;
  //kec
  with ZTable1 do begin
    Active:=False;
    TableName:='kecamatan';
    Active:=True;
    SetLength(bKec,RecordCount);
    I:=0;
    while (not Eof) do begin
      bKec[I].KODE:=FieldByName('KODE_KECAMATAN').AsString;
      bKec[I].NAMA:=FieldByName('TAMPIL').AsString;
      Inc(I);
      Next;
    end;
  end;
  //kota
  with ZTable1 do begin
    Active:=False;
    TableName:='kabkot';
    Active:=True;
    SetLength(bKabkot,RecordCount);
    I:=0;
    while (not Eof) do begin
      bKabkot[I].KODE:=FieldByName('KODE').AsString;
      bKabkot[I].NAMA:=FieldByName('TAMPIL').AsString;
      Inc(I);
      Next;
    end;
    cbKabkot.Clear;
    if(skodekec<>'')then
    begin
       btnGanda.Visible:=false;
       //btnMerah.Visible:=false;
       cbkabkot.items.add(getKabkot(skodekab));
       cbkabkot.itemindex:=0;
       sKabkot:=skodekab;
       cbkabkot.Enabled:=false;

       cbKec.items.add(getKec(skodeKec));
       cbkec.itemindex:=0;
       skec:=skodekec;
       cbkec.Enabled:=false;

       Active := False;
       TableName := 'desa';
       Filter := 'KODE_KECAMATAN = '+QuotedStr(sKec);
       Filtered := True;
       Active := True;
       First;
       cbdesa.Clear;
       cbdesa.Items.Add('');
       while (not Eof) do
          begin
            cbdesa.Items.Add(FieldByName('TAMPIL').AsString);
            Next;
          end;

    end
    else
    begin
      btnMerah.Visible:=false;
      if (skodekab='00') then begin
        cbKabkot.Items.Add('');
        for I := 0 to Length(bKabkot) - 1 do
          begin
            cbKabkot.Items.Add(bKabkot[i].NAMA);
          end;
        cbKabkot.ItemIndex:=-1;
      end
      else
      begin
        cbkabkot.items.add(getKabkot(skodekab));
        cbkabkot.itemindex:=0;
        sKabkot:=skodekab;
        cbkabkot.Enabled:=false;

        Active := False;
        TableName := 'kecamatan';
        Filter := 'KODE_KABKOT = '+QuotedStr(skodekab);
        filtered:=true;
        active:=true;

        cbkec.Items.Add('');
        while (not Eof) do
        begin
            cbkec.Items.Add(FieldByName('TAMPIL').AsString);
            Next;
        end;
        btnHapus.Visible := false;
        btnEdit.Visible := false;
        Button4.Visible := false;
        btnDaftar3.Visible := false;
        btnBuat3.Visible := false;
        Button3.Visible := false;
        btnKembalikan.Visible := false;
        btnRTRW.Visible:=false;
        btnCacat.Visible:=false;
      end;
    end;
  end;
  if(Date < EncodeDate( 2012, 10, 13 )) then
  begin
    //showMessage('tutup');
     btnHapus.Visible := false;
     btnEdit.Visible := false;
     Button4.Visible := false;
     btnDaftar3.Visible := false;
     btnBuat3.Visible := false;
     Button3.Visible := false;
     btnKembalikan.Visible := false;
  end;

  if(Date > EncodeDate( 2013, 2, 28 )) then
  begin
    //showMessage('tutup');
     btnHapus.Visible := false;
     btnEdit.Visible := false;
     Button4.Visible := false;
     btnDaftar3.Visible := false;
     btnBuat3.Visible := false;
     Button3.Visible := false;
     btnKembalikan.Visible := false;
  end;
end;

procedure TForm_NView.cbDesaChange(Sender: TObject);
var
  desa:String;
  desa_before : String;
begin
  desa_before := sdesa;
  btnMerah.Enabled:=false;
  btnRTRW.Enabled:=false;
  button4.Enabled:=false;
  btnedit.Enabled:=false;
  btnhapus.Enabled:=false;
  btnCacat.Enabled:=false;
  if (cbdesa.ItemIndex > 0) then
  begin
    btnGanda.Enabled:=false;
    btnMerah.Enabled:=false;
    desa := cbdesa.Items[cbdesa.ItemIndex];
    //
    ZTable1.Active := False;
    ZTable1.TableName := 'desa';
    ZTable1.Filter := 'TAMPIL = '+QuotedStr(desa)+' AND KODE_KECAMATAN = '+QuotedStr(sKec);
    ZTable1.Filtered := True;
    ZTable1.Active := True;
    ZTable1.First;
    sDesa := ZTable1.FieldByName('KODE_DESA').AsString;
    btnRefresh.Enabled:=true;
    if(desa_before <> sdesa) then begin
      btnBuat3.Enabled:=false;
      btnDaftar3.Enabled:=false;
      button4.Enabled:=false;
    end;
    //btnBuat3.Enabled:=true;
    //buat
  end
    else
  begin
    //btnGanda.Enabled:=true;
    //btnMerah.Enabled:=true;
    sDesa:='';
    btnTambah.Enabled:=False;
    btnEdit.Enabled:=False;
    btnDaftar3.Enabled:=false;
    Button1.enabled:=false;
    btnHapus.Enabled:=False;
    btnRefresh.Enabled:=false;
    Button2.Enabled:=false;
    btnCacat.Enabled:=false;
  end;
end;

procedure TForm_NView.PageControl1Change(Sender: TObject);
var
  i:Integer;
begin
  lblket2.Caption:='';
  if (PageControl1.ActivePage=TabSheet1) then begin
    if (posutama>=0) then begin
      btnEdit.Enabled:=True;
      for i := 1 to sgGanda.RowCount - 1
        do sgGanda.Rows[i].Clear;
      sgGanda.RowCount:=2;
      if (cekBGanda(tid+'-'+pid)) then
         showGanda(tid+'-'+pid);
      txtHal2.Enabled:=false;
      btnNext2.Enabled:=false;
      btnPrev2.Enabled:=false;
    end;
  end
    else
  begin
    //history
    if (prosesed) then begin
      if (PageControl2.ActivePage=TabSheet3) then begin
        FetchDB2(1);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet4) then begin
        FetchDB2(2);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet5) then begin
        FetchDB2(3);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet6) then begin
        FetchDB2(4);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet7) then begin
        FetchDB2(5);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet8) then begin
        FetchDB2(6);
        btnKembalikan.Enabled:=False;
      end;
    end;
  end;
end;

procedure TForm_NView.PageControl2Change(Sender: TObject);
begin
  if (prosesed) then begin
      if (PageControl2.ActivePage=TabSheet3) then begin
      //showmessage('1');
        FetchDB2(1);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet4) then begin
            //showmessage('2');
        FetchDB2(2);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet5) then begin
            //showmessage('3');
        FetchDB2(3);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet6) then begin
            //showmessage('4');
        FetchDB2(4);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet7) then begin
            //showmessage('5');
        FetchDB2(5);
        btnKembalikan.Enabled:=False;
      end
        else
      if (PageControl2.ActivePage=TabSheet8) then begin
            //showmessage('6');
        FetchDB2(6);
        btnKembalikan.Enabled:=False;
      end;
    end;
end;

procedure TForm_NView.FetchDB2(id:Integer);
var
  tambahan_where:String;
  kode:String;
  query:String;
  kKota:String;
  kKec:String;
  kDesa:String;
  tblName:String;
  i:Integer;
  count:Integer;
  gdata:Boolean;
  que:String;
begin
  lblHal2.Caption:='-';
  gdata:=False;
  for i := 1 to sgsejarah.RowCount - 1
  do sgsejarah.Rows[i].Clear;
  sgsejarah.RowCount:=2;
  if (sDesa<>'') then
    begin
      kode:=sDesa;
    end
  else if (sKec<>'') then
    begin
      kode:=sKec;
    end
  else if (sKabkot<>'') then
    begin
      kode:=sKabkot;
    end
  else
    begin
      kode:='';
    end;
  if (kode='') then
    query:='1'
  else
    query:='NAMA LIKE "pemilih_'+kode+'%"';
  ZQuery1.Active := False;
  query:= 'SELECT * FROM penyimpan WHERE '+query;
  ZQuery1.SQL.Text := query;
  ZQuery1.Active := True;
  ZQuery1.First;  //dapat tabel yang di simpan
  SetLength(bTabel2,ZQuery1.RecordCount);
  i:=0;
  count:=0;
  while (not ZQuery1.Eof) do
    begin
      gdata:=True;
      ZQuery2.Active := False;
      tblName:=ZQuery1.FieldByName('NAMA').AsString;
      ZQuery2.SQL.Clear;
      tambahan_where := '';
      if proses_asal = 2 then
        tambahan_where := ' AND STATUS1 = 0'
      else if proses_asal = 8 then
        tambahan_where := ' AND STATUS1 = 1';
      que:='SELECT COUNT(ID_USER) FROM '+tblname+' WHERE ';
      Case id of
        1 : que:=que+'STATUS2='+QuotedStr('1');
        2 : que:=que+'STATUS2='+QuotedStr('2');
        3 : que:=que+'STATUS2='+QuotedStr('3');
        4 : que:=que+'STATUS2='+QuotedStr('4');
        5 : que:=que+'STATUS2='+QuotedStr('5');
        6 : que:=que+'STATUS2='+QuotedStr('6');
      else ShowMessage('Unknown');
      end;
//      showmessage('1 '+que+tambahan_where);
      ZQuery2.SQL.Text:=que+tambahan_where;
      ZQuery2.Active := True;
      ZQuery2.First;  //tabel
      count:=ZQuery2.Fields[0].AsInteger;
      //ShowMessage(IntToStr(count));
      {if (ZQuery2.Fields[0].AsInteger>0) then begin
        bTabel2[i].ID:=ZQuery1.FieldByName('ID').AsString;
        bTabel2[i].TABEL:=ZQuery1.FieldByName('NAMA').AsString;
        bTabel2[i].COUNT:=count;
        Inc(i);
      end
        else
      SetLength(bTabel2,length(btabel2)-1);}
      ZQuery1.Next;
    end;
    lblKet2.Caption:=IntToStr(count)+' pemilih';
    jHal2:=count div bHal;
    totalhapus:=count;
    if ((count mod bHal)>0) then jHal2:=jHal2+1;
    TampilHalaman2(id,1);
end;

procedure TForm_NView.TampilHalaman2(id:Integer; Hal:Integer = 1);
var
  iter,i:Integer;
  tblName, tabel,iduser,tanda,query, tambahan_where:String;
begin
  tblName := 'pemilih_'+sdesa;
  tambahan_where := '';
  if proses_asal = 2 then
    tambahan_where := ' AND STATUS1 <> 1'
  else if proses_asal = 8 then
    tambahan_where := ' AND STATUS1 = 1';
  query:= 'SELECT ID_USER, NIK, NKK, NAMA, TEMPAT AS `TEMPAT_LAHIR`, TANGGAL AS `TANGGAL_LAHIR`, IBU, KAWIN AS `STATUS_PERKAWINAN`, KELAMIN AS `JENIS_KELAMIN`, ALAMAT, RW, RT, DUSUN FROM '+tblName+' WHERE ';
  Case id of
    1 : query:=query+'STATUS2='+QuotedStr('1');
    2 : query:=query+'STATUS2='+QuotedStr('2');
    3 : query:=query+'STATUS2='+QuotedStr('3');
    4 : query:=query+'STATUS2='+QuotedStr('4');
    5 : query:=query+'STATUS2='+QuotedStr('5');
    6 : query:=query+'STATUS2='+QuotedStr('6');
  else ShowMessage('Unknown');
  end;
  query:=query+tambahan_where+' ORDER BY RW,RT, NKK ASC';
//  showmessage('2 '+query);
  qryHistory.Active:=false;
  qryHistory.SQL.Clear;
  qryHistory.SQL.Text := query;
  qryHistory.Active := True;

  dsHistory.dataSet := qryHistory;

  {txtHal2.Enabled:=True;
  lblHal2.Caption := IntToStr(Hal)+' of '+IntToStr(jHal2);
  cHal2:=Hal;
  if (cHal2=1) then
    btnPrev2.Enabled:=False
  else
    btnPrev2.Enabled:=True;
  if (cHal2=jHal2) then
    btnNext2.Enabled:=False
  else
    btnNext2.Enabled:=True;
  //get to bpemilih
  GetData2(id,hal);
  cRow2:=1;
  while cRow2 <= totalhapus do //(cRow2<=bHal) and (crow2<=High(bpemilih2)) do
   begin
    sgSejarah.RowCount:=cRow2+1;
    tabel:=getTabel(bPemilih2[cRow2].ID);
    tabel:=getIdsimpan(tabel);
    iduser:=getIduser(bPemilih2[cRow2].ID);
    //
    sgSejarah.Cells[0,cRow2]:=IntToStr((cHal2-1)*bHal+cRow2);
    sgSejarah.Cells[1,cRow2]:=bPemilih2[cRow2].NIK;
    sgSejarah.Cells[2,cRow2]:=bPemilih2[cRow2].NKK;
    sgSejarah.Cells[3,cRow2]:=bPemilih2[cRow2].NAMA;
    sgSejarah.Cells[4,cRow2]:=bPemilih2[cRow2].TEMPAT;
    sgSejarah.Cells[5,cRow2]:=bPemilih2[cRow2].TANGGAL;
    sgSejarah.Cells[6,cRow2]:=bPemilih2[cRow2].IBU;
    sgSejarah.Cells[7,cRow2]:=bPemilih2[cRow2].AGAMA;
    sgSejarah.Cells[8,cRow2]:=bPemilih2[cRow2].KAWIN;
    sgSejarah.Cells[9,cRow2]:=bPemilih2[cRow2].KELAMIN;
    sgSejarah.Cells[10,cRow2]:=bPemilih2[cRow2].KELAINAN;
    sgSejarah.Cells[11,cRow2]:=bPemilih2[cRow2].ALAMAT;
    sgSejarah.Cells[12,cRow2]:=bPemilih2[cRow2].KOTA;
    sgSejarah.Cells[13,cRow2]:=bPemilih2[cRow2].KEC;
    sgSejarah.Cells[14,cRow2]:=bPemilih2[cRow2].DESA;
    sgSejarah.Cells[15,cRow2]:=bPemilih2[cRow2].RW;
    sgSejarah.Cells[16,cRow2]:=bPemilih2[cRow2].RT;
    sgSejarah.Cells[17,cRow2]:=bPemilih2[cRow2].DUSUN;
    sgSejarah.Cells[18,cRow2]:=bPemilih2[cRow2].KET;
    Case id of
      1 : sgSejarah.Cells[19,cRow2]:='Meninggal Dunia';
      2 : sgSejarah.Cells[19,cRow2]:='Data Fiktif';
      3 : sgSejarah.Cells[19,cRow2]:='TNI/POLRI';
      4 : sgSejarah.Cells[19,cRow2]:='Pindah';
      5 : sgSejarah.Cells[19,cRow2]:='Data Ganda';
      6 : sgSejarah.Cells[19,cRow2]:='Lain-lain';
    else ShowMessage('Unknown');
    end;
    Inc(crow2);
   end;
   //autosize
   for i := 0 to sgSejarah.ColCount - 1 do
    AutoSizeCol(sgSejarah, i);
   }
   //hapus seluruh elemen
   cxGrid2DBTableView1.BeginUpdate;
   cxGrid2DBTableView1.DataController.Filter.Clear;
   cxGrid2DBTableView1.ClearItems;

   cxGrid2DBTableView1.DataController.DataSource := dsHistory;
   cxGrid2DBTableView1.DataController.CreateAllItems;
   cxGrid2DBTableView1.Columns[0].Width:=40;
   cxGrid2DBTableView1.Columns[1].Width:=105;
   cxGrid2DBTableView1.Columns[2].Width:=105;
   cxGrid2DBTableView1.Columns[3].Width:=120;
   cxGrid2DBTableView1.Columns[4].Width:=90;
   cxGrid2DBTableView1.Columns[6].Width:=120;
   cxGrid2DBTableView1.Columns[9].Width:=150;
   cxGrid2DBTableView1.Columns[12].Width:=150;
   cxGrid2DBTableView1.EndUpdate;
end;

procedure TForm_NView.GetData2(id:Integer; Hal:Integer);
var
  tambahan_where:string;
  query:String;
  kKota:String;
  kKec:String;
  kDesa:String;
  tabel:TTabel;
  tblName,idsimpan,iduser,idganda:String;
  i:Integer;
  vRow,ujung,awal:Integer;
begin
  tambahan_where := '';
  if proses_asal = 2 then
    tambahan_where := ' AND STATUS1 <> 1'
  else if proses_asal = 8 then
    tambahan_where := ' AND STATUS1 = 1';
  dRow2:=1;
  vRow:=1;
  //cek
  ujung:=Hal*bHal;
  i:=0;
  if (jHal2>1) then begin
    for I := 0 to (Length(bTabel2)) - 1 do begin
      if (ujung<=bTabel2[i].COUNT) then
        break;
    end;
    if (i>0) then begin
      ujung:=ujung-btabel2[i-1].COUNT;
      if (ujung<bHal) then begin
        Dec(i);
        awal:=bTabel2[i].COUNT-(bHal-ujung);
      end else
        awal:=ujung-bHal;
    end
    else begin
      awal:=ujung-bHal;
    end;
  end
    else
  begin
    awal:=0;
    ujung:=bhal;
  end;
  //showmessage(IntToStr(length(btabel)));
  tblName:=btabel2[i].TABEL;
  idsimpan:=btabel2[i].ID;
  ZQuery1.Active := False;
  query:= 'SELECT * FROM '+tblName+' WHERE ';
  Case id of
    1 : query:=query+'STATUS2='+QuotedStr('1');
    2 : query:=query+'STATUS2='+QuotedStr('2');
    3 : query:=query+'STATUS2='+QuotedStr('3');
    4 : query:=query+'STATUS2='+QuotedStr('4');
    5 : query:=query+'STATUS2='+QuotedStr('5');
    6 : query:=query+'STATUS2='+QuotedStr('6');
  else ShowMessage('Unknown');
  end;
  query:=query+tambahan_where+' ORDER BY RW,RT, NKK ASC';
//  showmessage('2 '+query);
  ZQuery1.SQL.Text := query;
  ZQuery1.Active := True;
  ZQuery1.First;  //tabel simpan
  kKota:=Copy(tblName,9,2);
  kKota:=getKabkot(kKota);
  kKec:=Copy(tblName,9,5);
  kKec:=getKec(kKec);
  kDesa:=Copy(tblName,9,8);
  kDesa:=getDesa(kDesa);
  dRow2:=dRow2+ZQuery1.RecordCount;
  SetLength(bPemilih2,dRow2);
  while (not ZQuery1.Eof) do begin
    bPemilih2[vRow].ID :=tblName+ZQuery1.Fields[0].AsString;
    bPemilih2[vRow].NIK:=ZQuery1.Fields[1].AsString;
    bPemilih2[vRow].NKK:=ZQuery1.Fields[2].AsString;
    bPemilih2[vRow].NAMA:=ZQuery1.Fields[3].AsString;
    bPemilih2[vRow].TEMPAT:=ZQuery1.Fields[4].AsString;
    bPemilih2[vRow].TANGGAL:=ZQuery1.Fields[5].AsString;
    bPemilih2[vRow].IBU:=ZQuery1.Fields[6].AsString;
    bPemilih2[vRow].AGAMA:=ZQuery1.Fields[7].AsString;
    bPemilih2[vRow].KAWIN:=ZQuery1.Fields[8].AsString;
    bPemilih2[vRow].KELAMIN:=ZQuery1.Fields[9].AsString;
    bPemilih2[vRow].KELAINAN:=ZQuery1.Fields[10].AsString;
    bPemilih2[vRow].ALAMAT:=ZQuery1.Fields[11].AsString;
    bPemilih2[vRow].KOTA:=kKota;
    bPemilih2[vRow].KEC:=kKec;
    bPemilih2[vRow].DESA:=kDesa;
    bPemilih2[vRow].RW:=ZQuery1.Fields[12].AsString;
    bPemilih2[vRow].RT:=ZQuery1.Fields[13].AsString;
    bPemilih2[vRow].DUSUN:=ZQuery1.Fields[14].AsString;
    bPemilih2[vRow].KET:=ZQuery1.Fields[15].AsString;
    Inc(vrow);
    ZQuery1.Next;
  end;
  if ((ujung<bhal) and (jhal2>1)) then begin
    inc(i);
    tblName:=btabel2[i].TABEL;
    idsimpan:=btabel2[i].ID;
    ZQuery1.Active := False;
    query:= 'SELECT * FROM '+tblName+' WHERE ';
    Case id of
      1 : query:=query+'STATUS2='+QuotedStr('1');
      2 : query:=query+'STATUS2='+QuotedStr('2');
      3 : query:=query+'STATUS2='+QuotedStr('3');
      4 : query:=query+'STATUS2='+QuotedStr('4');
      5 : query:=query+'STATUS2='+QuotedStr('5');
      6 : query:=query+'STATUS2='+QuotedStr('6');
    else ShowMessage('Unknown');
    end;
    query:=query+' ORDER BY RW, RT, NKK ASC LIMIT 0,'+IntToStr(ujung)+tambahan_where;
//    showmessage('3 '+query);
    ZQuery1.SQL.Text := query;
    ZQuery1.Active := True;
    ZQuery1.First;  //tabel simpan
    kKota:=Copy(tblName,9,2);
    kKota:=getKabkot(kKota);
    kKec:=Copy(tblName,9,5);
    kKec:=getKec(kKec);
    kDesa:=Copy(tblName,9,8);
    kDesa:=getDesa(kDesa);
    dRow2:=dRow2+ZQuery1.RecordCount;
    SetLength(bPemilih2,dRow2);
    while (not ZQuery1.Eof) do begin
      bPemilih2[vRow].ID :=tblName+ZQuery1.Fields[0].AsString;
      bPemilih2[vRow].NIK:=ZQuery1.Fields[1].AsString;
      bPemilih2[vRow].NKK:=ZQuery1.Fields[2].AsString;
      bPemilih2[vRow].NAMA:=ZQuery1.Fields[3].AsString;
      bPemilih2[vRow].TEMPAT:=ZQuery1.Fields[4].AsString;
      bPemilih2[vRow].TANGGAL:=ZQuery1.Fields[5].AsString;
      bPemilih2[vRow].IBU:=ZQuery1.Fields[6].AsString;
      bPemilih2[vRow].AGAMA:=ZQuery1.Fields[7].AsString;
      bPemilih2[vRow].KAWIN:=ZQuery1.Fields[8].AsString;
      bPemilih2[vRow].KELAMIN:=ZQuery1.Fields[9].AsString;
      bPemilih2[vRow].KELAINAN:=ZQuery1.Fields[10].AsString;
      bPemilih2[vRow].ALAMAT:=ZQuery1.Fields[11].AsString;
      bPemilih2[vRow].KOTA:=kKota;
      bPemilih2[vRow].KEC:=kKec;
      bPemilih2[vRow].DESA:=kDesa;
      bPemilih2[vRow].RW:=ZQuery1.Fields[12].AsString;
      bPemilih2[vRow].RT:=ZQuery1.Fields[13].AsString;
      bPemilih2[vRow].DUSUN:=ZQuery1.Fields[14].AsString;
      bPemilih2[vRow].KET:=ZQuery1.Fields[15].AsString;
      Inc(vrow);
      ZQuery1.Next;
    end;
  end;
end;

procedure TForm_NView.sgGandaClick(Sender: TObject);
var
  pos,tots,i:Integer;
begin
  if ((sgGanda.Row>0) and (Length(bgridganda)>0) and (length(bgridganda)>sgganda.row)) then begin
      btnKembalikan.Enabled:=True;
      pos:=sgGanda.Row;
      //getID
      ptable2:=bgridganda[pos].nama;
      pid2:=bgridganda[pos].id;
  end;
end;

procedure TForm_NView.sgSejarahClick(Sender: TObject);
var
  pos,tots,i:Integer;
begin
  if (sgSejarah.Row>0) and (sgSejarah.Cells[0,1] <> '') then begin
      //showmessage(sgSejarah.Cells[0,1]);
      pos:=sgSejarah.Row;
      //getID
      ptable2:=Copy(bPemilih2[pos].ID,1,16);
      tots:=Length(bPemilih2[pos].ID)-16;
      pid2:=Copy(bPemilih2[pos].ID,17,tots);
      tid2:=getIdsimpan(ptable2);
      //
      btnKembalikan.Enabled:=True;
  end;
end;

{procedure TForm_NView.sgUtamaClick(Sender: TObject);
var
  pos,tots,i:Integer;
begin
  if (sgUtama.Row>0) and (sgUtama.Cells[1,1]<>'') then begin
      btnEdit.Enabled:=True;
      btnHapus.Enabled:=true;
      pos:=sgUtama.Row;
      //getID
      ptable:=Copy(bPemilih[pos].ID,1,16);
      tots:=Length(bPemilih[pos].ID)-16;
      pid:=Copy(bPemilih[pos].ID,17,tots);
      tid:=getIdsimpan(ptable);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if (cekBGanda(tid+'-'+pid)) then
           showGanda(tid+'-'+pid);
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;
end;}

function TForm_NView.cekBGanda(id:String):Boolean;
var
  res:Boolean;
  i:integer;
  temp:TGanda;
begin
  res:=false;
  //howmessage(id);
  for i:=0 to Length(bGanda)-1 do begin
    if (bGanda[i].ID1=id) then begin
      res:=True;
      break;
    end;
  end;
  Result:=res;
end;

procedure TForm_NView.showGanda(idganda:String);
var
  i,srow:Integer;
  tabel,tid,pid,id2,id1:String;
  idkabkot,idkec,idesa:String;
  temp:TStrings;
  ada:boolean;
begin
  srow:=1;

  for I := 0 to Length(bGanda) - 1 do begin
    if (bGanda[i].ID1=idganda) then begin
      id2:=bganda[i].ID2;
      temp := TStringList.Create;
      try
        ExtractStrings(['-'], [], PChar(id2), temp);
        tid := temp[0];
        pid := temp[1];
      finally
        temp.Free;
      end;

      tabel:=getSimpan(tid);
      idkabkot:=Copy(tabel,9,2);
      idkec:=Copy(tabel,9,5);
      idesa:=Copy(tabel,9,8);

      //no handle
      Inc(srow);
      SetLength(bGridganda,srow);
      sgGanda.RowCount:=srow;

      ZTable2.Active:=false;
      ZTable2.TableName:='pemilih_ganda';
      ZTable2.Filter:='ID_USER='+QuotedStr(id2);
      ZTable2.Filtered:=true;
      ZTable2.active:=true;
      ZTable2.First;
        sgGanda.Cells[0,srow-1]:=IntToStr(sRow-1);
        sgGanda.Cells[1,srow-1]:=ZTable2.FieldByName('NIK').AsString;
        sgGanda.Cells[2,srow-1]:=ZTable2.FieldByName('NKK').AsString;
        sgGanda.Cells[3,srow-1]:=ZTable2.FieldByName('NAMA').AsString;
        sgGanda.Cells[4,srow-1]:=ZTable2.FieldByName('TEMPAT').AsString;
        sgGanda.Cells[5,srow-1]:=ZTable2.FieldByName('TANGGAL').AsString;
        sgGanda.Cells[6,srow-1]:=ZTable2.FieldByName('IBU').AsString;
        sgGanda.Cells[7,srow-1]:=ZTable2.FieldByName('KAWIN').AsString;
        sgGanda.Cells[8,srow-1]:=ZTable2.FieldByName('KELAMIN').AsString;
        sgGanda.Cells[9,srow-1]:=ZTable2.FieldByName('ALAMAT').AsString;
        sgGanda.Cells[10,srow-1]:=getKabkot(idkabkot);
        sgGanda.Cells[11,srow-1]:=getKec(idkec);
        sgGanda.Cells[12,srow-1]:=getDesa(idesa);
        sgGanda.Cells[13,srow-1]:=ZTable2.FieldByName('RW').AsString;
        sgGanda.Cells[14,srow-1]:=ZTable2.FieldByName('RT').AsString;
        bGridganda[srow-1].ID:=pid;
        bGridganda[srow-1].NAMA:=tabel;
        

    end;
  end;
  lblKet2.Caption:=IntToStr(srow)+' data';
  for i := 0 to sgGanda.ColCount - 1 do
      AutoSizeCol(sgGanda, i);
end;

procedure TForm_NView.txtHalKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if key = VK_RETURN then
    getPage;
end;

procedure TForm_NView.getPage();
begin
    if ((txtHal.Text='') or (StrToInt(txtHal.Text)>jHal) or (StrToInt(txtHal.Text)<1)) then
      ShowMessage('Isi dahulu dengan halaman yang sesuai')
    else if (jHal=0) then
      ShowMessage('Tidak ada halaman yang dapat ditampilkan')
    else
      begin
        TampilHalaman(StrToInt(txtHal.Text));
      end;
end;

procedure TForm_NView.cxGrid1TableView1CellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
var
  a,pos,tots,i:integer;
  nama,nik:String;
begin
  a:=cxGrid1TableView1.Controller.FocusedRowIndex;
  if (cxGrid1TableView1.Controller.SelectedRowCount=1) then begin
    nama:=cxGrid1TableView1.Controller.SelectedRows[0].Values[3];
    nik:=cxGrid1TableView1.Controller.SelectedRows[0].Values[1];
  end;
  if (cxGrid1TableView1.Controller.SelectedRowCount<>1) then begin
    btnEdit.Enabled:=false;
    btnHapus.Enabled:=False;
  end;
  if ((nama<>'') AND (cxGrid1TableView1.Controller.SelectedRowCount=1)) then begin
    btnEdit.Enabled:=True;
    btnHapus.Enabled:=true;
    //
    pos:=cariPos(nama,nik);
    //
      //getID
    ptable:=Copy(bPemilih[pos].ID,1,16);
    tots:=Length(bPemilih[pos].ID)-16;
    pid:=Copy(bPemilih[pos].ID,17,tots);
    tid:=getIdsimpan(ptable);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if (cekBGanda(tid+'-'+pid)) then
           showGanda(tid+'-'+pid);
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;
end;

procedure TForm_NView.Button1Click(Sender: TObject);
var ckode:string;
begin
  tid:=getIdsimpan(ptable);
//  ShowMessage(skabkot+'-'+skec+'-'+sdesa);
  if(skodekec<>'')then ckode:=skodekec
  else ckode:=skodekab;
  ftambah:=TForm_Ftambah.create(Application,ckode,sKabkot,sKec,sDesa);
  tambahGb.Visible:=false;
end;

procedure TForm_NView.btnDaftarClick(Sender: TObject);
var
  nama,nik:String;
  i,j,pt,tots:integer;
  pemilihs: TStringList;
begin
  if (cxGrid1TableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilihs := Tstringlist.Create;
    with cxGrid1TableView1.Controller do begin
        for i:=0 to SelectedRowCount-1 do begin
          nama:=SelectedRows[i].Values[3];
          nik:=SelectedRows[i].Values[1];
          pt:=cariPos(nama,nik);
          tots:=Length(bPemilih[pt].ID)-16;
          pemilihs.Add(Copy(bPemilih[pt].ID,17,tots));
//          ShowMessage(Copy(bPemilih[pt].ID,17,tots));
        end;
    end;
    fDaftar:= TForm_DaftarkanTPS.Create(Application,sdesa,pemilihs,skode);
  end
    else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
end;

procedure TForm_NView.cxGrid1TableView1SelectionChanged(
  Sender: TcxCustomGridTableView);
var
  a,pos,tots,i:integer;
  nama,nik:String;
begin
  a:=cxGrid1TableView1.Controller.FocusedRowIndex;
  if (cxGrid1TableView1.Controller.SelectedRowCount=1) then begin
    nama:=cxGrid1TableView1.Controller.SelectedRows[0].Values[3];
    nik:=cxGrid1TableView1.Controller.SelectedRows[0].Values[1];
  end;
  if (cxGrid1TableView1.Controller.SelectedRowCount<>1) then begin
    btnEdit.Enabled:=false;
    btnHapus.Enabled:=False;
  end;
  if ((nama<>'') AND (cxGrid1TableView1.Controller.SelectedRowCount=1)) then begin
    btnEdit.Enabled:=True;
    btnHapus.Enabled:=true;
    //
    pos:=cariPos(nama,nik);
    //
      //getID
    ptable:=Copy(bPemilih[pos].ID,1,16);
    tots:=Length(bPemilih[pos].ID)-16;
    pid:=Copy(bPemilih[pos].ID,17,tots);
    tid:=getIdsimpan(ptable);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if (cekBGanda(tid+'-'+pid)) then
           showGanda(tid+'-'+pid);
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;
end;

procedure TForm_NView.Button4Click(Sender: TObject);
begin
  //tambahGb.Visible := True;
  PopupMenu1.Popup(Mouse.CursorPos.X,Mouse.CursorPos.Y);
end;

procedure TForm_NView.cxGrid1DBTableView1CustomDrawCell(
  Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
  AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var
  Rect:TRect;
  Atext:String;
begin
  if AViewInfo.GridRecord.Values[14]<>'0' then
  begin
    ACanvas.Brush.Color:=clFuchsia;
    ACanvas.Font.Color:=clBlack;
  end;
  if(AViewInfo.Selected) and (Screen.ActiveControl = Sender.Site) then begin
    ACanvas.Brush.Color := clBlue;
    ACanvas.Font.Color := clWhite;
  end;
    //
  {if AViewInfo.GridRecord.Values[7]='S' then
    AViewInfo.GridRecord.Values[7]:='SUDAH'
  else if AViewInfo.GridRecord.Values[7]='B' then
    AViewInfo.GridRecord.Values[7]:='BELUM'
  else
    AViewInfo.GridRecord.Values[7]:='CERAI';
    //}
  {if AViewInfo.GridRecord.Values[8]='L' then
    begin
        ACanvas.Canvas.FillRect( AViewInfo.Bounds );
        Rect := AViewInfo.TextAreaBounds;
        ACanvas.DrawText('To Order', Rect, cxAlignLeft or cxShowEndEllipsis);
        ADone := True;
     end
  else if AViewInfo.GridRecord.Values[8]='P' then}

end;

procedure TForm_NView.cxGrid1DBTableView1CellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
var
  a,pos,tots,i:integer;
  iduser,nama,nik, ganda:String;
begin
  //a:=cxGrid1DBTableView1.Controller.FocusedRowIndex;
  if (cxGrid1DBTableView1.Controller.SelectedRowCount=1) then begin
    nama:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[3];
    ganda:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[3];
    nik:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[1];
    iduser:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[0];
//    ShowMessage(nama+'-'+nik);
  end;
  if (cxGrid1DBTableView1.Controller.SelectedRowCount<>1) then begin
    btnEdit.Enabled:=false;
    //btnHapus.Enabled:=False;
  end;
  if ((cxGrid1DBTableView1.Controller.SelectedRowCount>1)) then begin
    btnHapus.Enabled:=true;
    btnRTRW.Enabled:=true;
    btnMerah.Enabled:=true;
    btnCacat.Enabled:=true;
  end;
  if ((cxGrid1DBTableView1.Controller.SelectedRowCount=1)) then begin
    btnEdit.Enabled:=True;
    btnHapus.Enabled:=true;
    btnRTRW.Enabled:=true;
    btnMerah.Enabled:=true;
    btnCacat.Enabled:=true;
    //
    //pos:=cariPos(nama,nik);
    //
      //getID
    ptable:='pemilih_'+sdesa;
    //tots:=Length(bPemilih[pos].ID)-16;
    pid:=iduser;
    tid:=getIdsimpan(ptable);
//    showmessage(ptable+'-'+tid+'-'+pid);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if(ganda = '1') then begin
          if (cekBGanda(tid+'-'+pid)) then
            showGanda(tid+'-'+pid);
        end;
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;
end;

procedure TForm_NView.JvThread1Execute(Sender: TObject; Params: Pointer);
var
  i:integer;
  tabel:string;
  iduser,query:string;
begin
  CoInitialize(nil);


  {with zquery1 do begin
      active:=false;
      sql.clear;
      sql.text:='SELECT * FROM pemilih_'+sdesa+' WHERE STATUS2="0" AND GANDA="1" ORDER BY NKK ASC';
      active:=true;
      first;
    end;
    while not zquery1.Eof do begin
      tabel:=getIdsimpan('pemilih_'+sdesa);
      iduser:=zquery1.fieldbyname('ID_USER').AsString;}
      tabel:=getIdsimpan('pemilih_'+sdesa);
      with ZQuery2 do begin
        Active:=false;
        sql.Clear;
        query:='SELECT * FROM data_ganda WHERE ID_USER1 LIKE '+quotedstr(tabel+'-%');
        sql.Text:=query;
        Active:=true;
        First;
        //memo1.Text:=(query);
        if (FieldByName('ID_USER1').AsString<>'') then begin
          while (not Eof) do begin
            SetLength(bGanda,(Length(bGanda)+1));
            bGanda[Length(bGanda)-1].ID1:=FieldByName('ID_USER1').AsString;
            bGanda[Length(bGanda)-1].ID2:=FieldByName('ID_USER2').AsString;
            bGanda[Length(bGanda)-1].KET:=FieldByName('KETERANGAN').AsInteger;
            Next;
          end;
        end;
      //
        Active:=false;
        sql.Clear;
        query:='SELECT * FROM data_ganda WHERE ID_USER2 LIKE '+quotedstr(tabel+'-%');
        sql.Text:=query;
        Active:=true;
        First;
        if (FieldByName('ID_USER2').AsString<>'') then begin
          while (not Eof) do begin
            SetLength(bGanda,(Length(bGanda)+1));
            bGanda[Length(bGanda)-1].ID1:=FieldByName('ID_USER2').AsString;
            bGanda[Length(bGanda)-1].ID2:=FieldByName('ID_USER1').AsString;
            bGanda[Length(bGanda)-1].KET:=FieldByName('KETERANGAN').AsInteger;
            Next;
          end;
        end;
      end;
//      ZQuery1.Next;
//    end;
  CoUnInitialize;
  if JvThread1.Terminated then
  begin
    Exit;
  end;
end;

procedure TForm_NView.Button3Click(Sender: TObject);
var kode1,kode2,query,idx:string;
  temp:tstringlist;
begin
  if ((sgGanda.Row>0) and (Length(bgridganda)>0) and (length(bgridganda)>sgganda.row)) then begin
      kode1:=getIdsimpan(ptable)+'-'+pid;
      kode2:=getIdsimpan(ptable2)+'-'+pid2;
      {with zquery1 do
      begin
        active:=false;
        sql.clear;
        sql.text:='update data_ganda set VERIFIKASI=1 where (ID_USER1='+quotedstr(kode1)+' AND ID_USER2='+quotedstr(kode2)+') OR (ID_USER1='+quotedstr(kode2)+' AND ID_USER2='+quotedstr(kode1)+')';
        //showmessage(sql.text);
        //execsql;
      end;}

      //ganda
    //cek data_ganda
    with ZQuery1 do begin
      Active:=false;
      sql.Clear;
      query:='SELECT * FROM data_ganda WHERE ID_USER1='+QuotedStr(kode2)+' OR ID_USER2='+QuotedStr(kode2);
      SQL.Text:=query;
      Active:=true;
    end;
    //kalau cuma sepasang, ubah
    if ZQuery1.RecordCount>=1 then begin
      if (ZQuery1.FieldByName('ID_USER1').AsString=kode2) then
        idx:=ZQuery1.FieldByName('ID_USER2').AsString
      else
        idx:=ZQuery1.FieldByName('ID_USER1').AsString;
      with ZQuery1 do begin
        Active:=false;
        sql.Clear;
        query:='UPDATE '+ptable2+' SET GANDA="0" WHERE ID_USER='+pid2;
        SQL.Text:=query;
        ExecSQL;
        //
        Active:=false;
        sql.Clear;
        if atb=1 then
          query:='DELETE FROM data_ganda WHERE ID_USER1='+QuotedStr(kode2)+' OR ID_USER2='+QuotedStr(kode2)
        else
          query:='DELETE FROM data_ganda WHERE (ID_USER1='+QuotedStr(kode2)+' AND ID_USER2='+QuotedStr(kode1)+') OR (ID_USER1='+QuotedStr(kode1)+' AND ID_USER2='+QuotedStr(kode2)+')';
        SQL.Text:=query;
        ExecSQL;
      end;
    end;
    /////
    with ZQuery1 do begin
      Active:=false;
      sql.Clear;
      query:='SELECT * FROM data_ganda WHERE ID_USER1='+QuotedStr(idx)+' OR ID_USER2='+QuotedStr(idx);
      SQL.Text:=query;
      Active:=true;
    end;
    //kalau sudah habis, ubah
    if (ZQuery1.RecordCount<1) and (idx<>'') then begin
       with ZQuery1 do begin
        Active:=false;
        sql.Clear;
        temp := TStringList.Create; //1
        try
          ExtractStrings(['-'], [], PChar(idx), temp);
           tidx := temp[0];
           pidx := temp[1];
        finally
          temp.Free;
        end;
        query:='SELECT * FROM penyimpan WHERE ID='+tidx;
        sql.Text:=query;
        active:=True;
        ptabelx:=FieldByName('NAMA').AsString;
        //
        Active:=false;
        sql.Clear;
        query:='UPDATE '+ptabelx+' SET GANDA="0" WHERE ID_USER='+pidx;
        SQL.Text:=query;
        ExecSQL;
       end;
    end;
    showmessage('Proses bukan data ganda berhasil');
  end;
end;

procedure TForm_NView.JvThread2Execute(Sender: TObject; Params: Pointer);
var
  kode:String;
  query:String;
  kKota:String;
  kKec:String;
  kDesa:String;
  tblName:String;
  i:Integer;
  where_tambahan:String;
  que:String;
begin
  CoInitialize(nil);
for i := 1 to sgGanda.RowCount - 1
    do sgGanda.Rows[i].Clear;
  sgGanda.RowCount:=2;
  for i := 1 to sgSejarah.RowCount - 1
    do sgSejarah.Rows[i].Clear;
  sgSejarah.RowCount:=2;
  where_tambahan:='';
  if (proses_asal = 2) then
    where_tambahan:=' AND (STATUS1 = 0 OR STATUS1 = 2)'
  else if (proses_asal = 8) then
    where_tambahan:=' AND STATUS1 = 1';
  //
  if (sDesa<>'') then
    begin
      kode:=sDesa;
    end
  else if (sKec<>'') then
    begin
      kode:=sKec;
    end
  else if (sKabkot<>'') then
    begin
      kode:=sKabkot;
    end
  else
    begin
      kode:='';
    end;
  if (kode='') then
    query:='1'
  else
    query:='NAMA LIKE "pemilih_'+kode+'%"';
  ZQuery1.Active := False;
  query:= 'SELECT * FROM penyimpan WHERE '+query;
  ZQuery1.SQL.Text := query;
  ZQuery1.Active := True;
  ZQuery1.First;  //dapat tabel yang di simpan
  SetLength(bTabel,ZQuery1.RecordCount);
  i:=0;
  countthread:=0;
  count2thread:=0;
  count3thread:=0;
  while (not ZQuery1.Eof) do
    begin
      gdata:=True;
      ZQuery2.Active := False;
      tblName:=ZQuery1.FieldByName('NAMA').AsString;
      ZQuery2.SQL.Clear;
      que:='SELECT COUNT(*) FROM '+tblname;
      que:=que+' WHERE STATUS2="0"'+where_tambahan;
//      showmessage(que);
      ZQuery2.SQL.Text:=que;
      ZQuery2.Active := True;
      ZQuery2.First;  //tabel
      countthread:=countthread+ZQuery2.Fields[0].AsInteger;
      //ShowMessage(IntToStr(count));
      if (ZQuery2.Fields[0].AsInteger>0) then begin
        bTabel[i].ID:=ZQuery1.FieldByName('ID').AsString;
        bTabel[i].TABEL:=ZQuery1.FieldByName('NAMA').AsString;
        bTabel[i].COUNT:=countthread;
        Inc(i);
      end
        else
        SetLength(bTabel,length(btabel)-1);
      //GANDA COUNT
      ZQuery2.SQL.Clear;
      que:='SELECT COUNT(ID_USER) FROM '+tblname+' where GANDA<>0 AND STATUS2 = 0 '+where_tambahan;
      //que:='SELECT COUNT(*) FROM data_ganda'; FIXME
      //que:=que+' WHERE ID_USER1 LIKE "'+getIdsimpan(tblname)+'-%" OR ID_USER2 LIKE "'+getIdsimpan(tblname)+'-%"'; FIXME
//      showmessage(que);
      ZQuery2.SQL.Text:=que;
      ZQuery2.Active := True;
      ZQuery2.First;  //tabel
      count2thread:=count2thread+ZQuery2.Fields[0].AsInteger;

      ZQuery2.SQL.Clear;
      que:='SELECT COUNT(ID_USER) FROM '+tblname+' where TPS=0 AND STATUS2 = 0 '+where_tambahan;
      //que:='SELECT COUNT(*) FROM data_ganda'; FIXME
      //que:=que+' WHERE ID_USER1 LIKE "'+getIdsimpan(tblname)+'-%" OR ID_USER2 LIKE "'+getIdsimpan(tblname)+'-%"'; FIXME
//      showmessage(que);
      ZQuery2.SQL.Text:=que;
      ZQuery2.Active := True;
      ZQuery2.First;  //tabel
      count3thread:=count3thread+ZQuery2.Fields[0].AsInteger;
      //
      ZQuery1.Next;
    end;
    
    CoUnInitialize;
  if JvThread2.Terminated then
  begin
    Exit;
  end;
end;

procedure TForm_NView.JvThread2FinishAll(Sender: TObject);
begin
  jHal:=countthread div bHal;
  if ((countthread mod bHal)>0) then jHal:=jHal+1;
  //if (gdata and (countthread>0)) then
  TampilHalaman(1);
  //text ket
  lblKet.Caption:=IntToStr(countthread)+' orang';
  lblKetmerah.Caption:=IntToStr(count2thread)+' dicurigai ganda';
  lblMerah2.Caption:=IntToStr(count3thread)+' belum terdaftar di TPS';

end;

procedure TForm_NView.JvThread3Execute(Sender: TObject; Params: Pointer);
begin
with zquery3 do begin
      active:=false;
      sql.clear;
      sql.text:='SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT LAHIR`, a.TANGGAL AS `TANGGAL LAHIR`, a.IBU, a.KAWIN AS `STATUS PERKAWINAN`, a.KELAMIN AS `JENIS KELAMIN`, a.ALAMAT, a.RW, a.RT, b.NAMA AS `DI TPS`, a.GANDA  FROM pemilih_'+sdesa+' a LEFT JOIN daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0" ORDER BY a.NKK ASC';
      active:=true;
   end;

end;

procedure TForm_NView.JvThread3FinishAll(Sender: TObject);
begin
  sleep(100);
   DataSource1.DataSet:=zquery3;
   cxGrid1DBTableView1.DataController.DataSource:=DataSource1;
   cxGrid1DBTableView1.DataController.CreateAllItems;

   sleep(100);
    //
    JvThread1.ThreadDialog:=JvThreadSimpleDialog1;
    JvThread1.Execute(self);
    sleep(100);
end;

procedure TForm_NView.ambahSatuPemilih1Click(Sender: TObject);
var ckode:string;
begin
  tid:=getIdsimpan(ptable);
//  ShowMessage(skabkot+'-'+skec+'-'+sdesa);
  if(skodekec<>'')then ckode:=skodekec
  else ckode:=skodekab;

  ftambah:=TForm_Ftambah.create(Application,ckode,sKabkot,sKec,sDesa,proses_asal,username);
end;

procedure TForm_NView.ambahDuaatauLebihPemilih1Click(Sender: TObject);
begin
  fTambahp:= TForm_TambahPemilih.Create(Application,sdesa,proses_asal,username);
end;

procedure TForm_NView.InitFilterGrid;
var
    I: Integer;
begin
    {Sets the widths of the columns in the filter grid grdFilter equal to those
     of the data grid grdData.}

{    tsDBGrid2.Cols := tsDBGrid1.Cols;
    for I := 1 to tsDBGrid2.Cols do
    begin
        tsDBGrid2.Col[I].Width := tsDBGrid1.Col[I].Width;
    end;}
end;

function TForm_NView.GetFilter: string;
var
    I, J, K: Integer;
    SearchString: string;
    SearchStringStart: string;
    TekenFound: Boolean;
    QuoteChecked: Boolean;
    FirstCharacter: Integer;
    NumberOfQuotes: Integer;
    FieldName: string;
begin
    {Calculates the filter condition, given the values entered in the filter
     grid grdFilter.

     The filter grid has it's StoreData property set to true, so any value
     typed into the grid is automatically saved. This routine then uses the
     values to calculate the filter.}

{    Result := '';
    for I := 1 to tsDBGrid2.Cols do
    begin
        SearchString := string(tsDBGrid2.Cell[I,1]);
        FieldName := TsDBGrid1.Col[I].FieldName;
        if (SearchString <> '') and (FieldName <> '') then
        begin
            if Result <> '' then Result := Result + ' AND ';
            Result := Result + '(' + FieldName;
            Result := Result + ' LIKE ' + QuotedStr(SearchString + '*')+' )';
            //showMessage(Result);
        end;
    end;}
end;

procedure TForm_NView.tsDBGrid2KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  {Sets the new filter condition when the Enter key is hit.}
{    if (Key = VK_RETURN) and not TsDBGrid2.ComboVisible then
    begin
        SetFilter;
        Key := 0;
    end;}
end;

procedure TForm_NView.SetFilter;
var
    FilterString: string;
    OldLeftCol: Longint;
    OldFilter: string;
begin
    {Calculates the filter condition given the filter values entered, and
     assigns the filter to the table.}

   { Screen.Cursor := crHourGlass;

    OldLeftCol := tsDBGrid1.LeftCol;
    tsDBGrid1.EnableRedraw := false;
    OldFilter := DataSource1.DataSet.Filter;

    FilterString := GetFilter;
    DataSource1.DataSet.Filtered := false;
    //showMessage(filterstring);
    try
        try
            DataSource1.DataSet.Filter := Filterstring;
            DataSource1.DataSet.Filtered := true;
            DataSource1.DataSet.First;
            TsDBGrid1.LeftCol := OldLeftCol;
        finally
            TsDBGrid1.EnableRedraw := true;
        end;
    except
        DataSource1.DataSet.Filter := OldFilter;
        DataSource1.DataSet.Filtered := true;
        DataSource1.DataSet.First;
        TsDBGrid1.Rows := DataSource1.DataSet.RecordCount;

        TsDBGrid1.LeftCol := OldLeftCol;
        TsDBGrid1.EnableRedraw := true;
        ShowMessage('Filter is incorrect. Please try again.');
    end;

    TsDBGrid1.Refresh;
    Screen.Cursor := crDefault;}
end;

procedure TForm_NView.tsDBGrid1ColMoved(Sender: TObject; ToDisplayCol,
  Count: Integer; ByUser: Boolean);
var
  ACol : Longint;
begin
{  for ACol := 1 to tsDBGrid1.Cols do
  tsDBGrid2.Col[tsDBGrid1.DataColnr[ACol]].DisplayCol := ACol;}
end;

procedure TForm_NView.tsDBGrid1ColResized(Sender: TObject;
  RowColnr: Integer);
begin
{  if(jadi = true) then
  tsDBGrid2.Col[RowColnr].Width := tsDBGrid1.Col[RowColnr].Width;}
end;

procedure TForm_NView.tsDBGrid1TopLeftChanged(Sender: TObject;
  OldCol: Integer; OldRow: Variant; NewCol: Integer; NewRow: Variant;
  ByUser: Boolean);
begin
{  if not FSettingTopLeft then
    begin
        FSettingTopLeft := True;
        tsDBGrid2.LeftCol := NewCol;
        tsDBGrid2.Update;
        FSettingTopLeft := False;
    end;}
end;

procedure TForm_NView.tsDBGrid2TopLeftChanged(Sender: TObject;
  OldCol: Integer; OldRow: Variant; NewCol: Integer; NewRow: Variant;
  ByUser: Boolean);
begin
{  if not FSettingTopLeft then
    begin
        FSettingTopLeft := True;
        tsDBGrid1.LeftCol := NewCol;
        tsDBGrid1.Update;
        FSettingTopLeft := False;
    end;}
end;

procedure TForm_NView.tsDBGrid1GetDrawInfo(Sender: TObject;
  DataCol: Integer; DataRow: Variant; var DrawInfo: TtsDrawInfo);
begin
{  with TsDBGrid1 do
    begin
        //If ItemsTotal <> AmountPaid set the background color to clAqua.
        //To access the fields, use the column's Field property as indicated
        //below. This allows you to access the active record in the grid, which
        //is the record currently being drawn.
        {if Col['GANDA'].Field.AsInteger = 1 then
            DrawInfo.Color := clAqua;            }
//    end;
end;

procedure TForm_NView.tsDBGrid1ClickCell(Sender: TObject;
  DataColDown: Integer; DataRowDown: Variant; DataColUp: Integer;
  DataRowUp: Variant; DownPos, UpPos: TtsClickPosition);
var
  a,pos,tots,i:integer;
  iduser,nama,nik:String;
begin
{  //a:=cxGrid1DBTableView1.Controller.FocusedRowIndex;
  if (tsDBGrid1.SelectedRows.Count=1) then begin

    nik:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[1];
    iduser:=cxGrid1DBTableView1.Controller.SelectedRows[0].Values[0];
//    ShowMessage(nama+'-'+nik);
  end;
  if (cxGrid1DBTableView1.Controller.SelectedRowCount<>1) then begin
    btnEdit.Enabled:=false;
    btnHapus.Enabled:=False;
  end;
  if ((nama<>'') AND (cxGrid1DBTableView1.Controller.SelectedRowCount=1)) then begin
    btnEdit.Enabled:=True;
    btnHapus.Enabled:=true;
    //
    //pos:=cariPos(nama,nik);
    //
      //getID
    ptable:='pemilih_'+sdesa;
    //tots:=Length(bPemilih[pos].ID)-16;
    pid:=iduser;
    tid:=getIdsimpan(ptable);
//    showmessage(ptable+'-'+tid+'-'+pid);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if (cekBGanda(tid+'-'+pid)) then
           showGanda(tid+'-'+pid);
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;}
end;

procedure TForm_NView.DBGrid1ColumnMoved(Sender: TObject; FromIndex,
  ToIndex: Integer);
var
  ACol : Longint;
begin
{  showmessage('aye');
  for ACol := 0 to DBGrid1.Columns.Count do
  tsDBGrid2.Col[ACol].DisplayCol := ACol+1;}
end;

procedure TForm_NView.DBGrid1CellClick(Column: TColumn);
var
  a,pos,tots,i:integer;
  iduser,nama,nik:String;
begin
  //a:=cxGrid1DBTableView1.Controller.FocusedRowIndex;
  {showmessage('blara'+inttostr(DBGrid1.SelectedIndex));
  if (DBGrid1.SelectedRows.Count=1) then begin
    nama:=DBGrid1.SelectedRows.Items[3];
    showmessage(nama);
{    nama:=DBGrid1.SelectedRows[0].Values[3];
    nik:=DBGrid1.SelectedRows[0].Values[1];
    iduser:=DBGrid1.SelectedRows[0].Values[0];
//    ShowMessage(nama+'-'+nik);
  end;
  if (DBGrid1.SelectedRows.Count<>1) then begin
    btnEdit.Enabled:=false;
    btnHapus.Enabled:=False;
  end;
  if ((nama<>'') AND (DBGrid1.SelectedRows.Count=1)) then begin
    btnEdit.Enabled:=True;
    btnHapus.Enabled:=true;
    //
    //pos:=cariPos(nama,nik);
    //
      //getID
    ptable:='pemilih_'+sdesa;
    //tots:=Length(bPemilih[pos].ID)-16;
    pid:=iduser;
    tid:=getIdsimpan(ptable);
//    showmessage(ptable+'-'+tid+'-'+pid);
      //
      btnKembalikan.Enabled:=false;
      if (PageControl1.ActivePage=TabSheet1) then begin
        //data ganda
        for i := 1 to sgGanda.RowCount - 1
          do sgGanda.Rows[i].Clear;
        sgGanda.RowCount:=2;
        if (cekBGanda(tid+'-'+pid)) then
           showGanda(tid+'-'+pid);
        txtHal2.Enabled:=false;
        btnNext2.Enabled:=false;
        btnPrev2.Enabled:=false;
      end;
  end;          }
end;

procedure TForm_NView.cxGrid1DBTableView1DataControllerFilterChanged(
  Sender: TObject);
var
  filter, hasil, temp1, temp2 : string;
  filterarr : tstringlist;
  i : integer;
begin
  hasil := '';
  filter := cxGrid1DBTableView1.DataController.Filter.FilterText;
  filterarr := TStringList.Create;
  try
    ExtractStrings(['('], [], PChar(filter), filterarr);
    for i:=0 to filterarr.count-1 do begin
      temp1 := copy(filterarr[i],1,9);
      if(temp1 = 'NAMA LIKE') then begin
        temp2 := copy(filterarr[i],1,11)+'%'+copy(filterarr[i],12,length(filterarr[i]));
        //showmessage(temp2);
      end
      else
        temp2 := filterarr[i];
      hasil := hasil + '(' + temp2;
    end;
  finally
    filterarr.Free;
  end;
//  cxGrid1DBTableView1.DataController.Filter
end;

procedure TForm_NView.cxGrid1DBTableView1SelectionChanged(
  Sender: TcxCustomGridTableView);
var
  jumlah_row : integer;
begin
  jumlah_row := cxGrid1DBTableView1.DataController.RowCount;
  lblfilter.Caption := 'Jumlah Terfilter: '+inttostr(jumlah_row);
end;

procedure TForm_NView.cxGrid1DBTableView1EditKeyUp(
  Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
  AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState);
var
  jumlah_row : integer;
begin
  jumlah_row := cxGrid1DBTableView1.DataController.RowCount;
  lblfilter.Caption := 'Jumlah Terfilter: '+inttostr(jumlah_row);
end;

procedure TForm_NView.Button5Click(Sender: TObject);
begin
  try
    if openDlg.Execute then
      ExportGridToExcel(openDlg.FileName,cxGrid1,False);
  finally
    MessageDlg('Export Berhasil',mtConfirmation,[mbOk],0);
  end;
end;

procedure TForm_NView.threadKembaliExecute(Sender: TObject;
  Params: Pointer);
var
  idx:integer;
  id_pemilih, query, iQue, idtgl, tabel:string;
begin
  tabel:=getIdSimpan('pemilih_'+sdesa);
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'INSERT INTO tanggal (TANGGAL) VALUES ("'+tanggal+'")';
    ExecSQL;
  end;
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'SELECT * FROM tanggal ORDER BY ID_TANGGAL DESC';
    Active:=True;
    idtgl := FieldByName('ID_TANGGAL').AsString;  //dapat ID_TGL
  end;
  for idx:=0 to pemilih_kembali.Count-1 do begin
        id_pemilih:=pemilih_kembali[idx];
        with ZQuery1 do begin
          active:=false;
          sql.Clear;
          query:='SELECT * FROM pemilih_'+sdesa+' WHERE ID_USER='+id_pemilih;
  //      ShowMessage(query);
          sql.Text:=query;
          Active:=true;
          first;
          iQue:='INSERT INTO `history` (ID_USER, `NIK`, `NKK`, `NAMA`, `TEMPAT`, `TANGGAL`, '+
          '`IBU`, `AGAMA`, `KAWIN`, `KELAMIN`, `KELAINAN`, `ALAMAT`, `RW`, `RT`, `DUSUN`, `KET`, '+
          '`ID_TANGGAL`, TPS, STATUS1, STATUS2, GANDA, STATUS3, STATUSP, ALASANP'+
          ',CACAT,PENDIDIKAN,PEKERJAAN,STATUSR,WN,USERNAME,KET_AKSI) VALUES '+
          '('+QuotedStr(tabel+'-'+FieldByName('ID_USER').AsString)+
          ','+QuotedStr(HandleSpec(FieldByName('NIK').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('NKK').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('NAMA').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('TEMPAT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('TANGGAL').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('IBU').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('AGAMA').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KAWIN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KELAMIN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KELAINAN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('ALAMAT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('RW').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('RT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('DUSUN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KET').AsString))+
          ','+FieldByName('ID_TANGGAL').AsString+
          ','+FieldByName('TPS').AsString+
          ','+QuotedStr(FieldByName('STATUS1').AsString)+
          ','+QuotedStr(FieldByName('STATUS2').AsString)+
          ','+QuotedStr(FieldByName('GANDA').AsString)+
          ','+QuotedStr(FieldByName('STATUS3').AsString)+
          ','+QuotedStr(FieldByName('STATUSP').AsString)+
          ','+QuotedStr(FieldByName('ALASANP').AsString)+
          ','+QuotedStr(FieldByName('CACAT').AsString)+
          ','+QuotedStr(FieldByName('PENDIDIKAN').AsString)+
          ','+QuotedStr(FieldByName('PEKERJAAN').AsString)+
          ','+QuotedStr(FieldByName('STATUSR').AsString)+
          ','+QuotedStr(FieldByName('WN').AsString)+
          ','+QuotedStr(username)+
          ','+QuotedStr('3')+
          ')';
          //
          active:=false;
          sql.Clear;
  //        ShowMessage(ique);
          sql.Text:=ique;
          ExecSQL;
          //
          active:=false;
          sql.Clear;

          query:='UPDATE pemilih_'+sdesa+' SET STATUS2="0", KET = "", ID_TANGGAL = "'+idtgl+'" WHERE ID_USER='+id_pemilih;
        //ShowMessage(query);
          sql.Text:=query;
          ExecSQL;
        end;
      end;
end;

procedure TForm_NView.threadKembaliFinishAll(Sender: TObject);
begin
  ShowMessage('Data telah dikembalikan');
end;

procedure TForm_NView.cxGrid2DBTableView1CellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
begin
  btnKembalikan.Enabled:=True;
  btnPermanen.Enabled:=True;
end;

function TForm_NView.HandleSpec(Asal: String):String;
var
  temp:string;
begin
  temp := StringReplace(asal, '''', '',[rfReplaceAll, rfIgnoreCase]);
  temp := StringReplace(temp, '\', '',[rfReplaceAll, rfIgnoreCase]);
  result := temp;
end;

procedure TForm_NView.btnGandaClick(Sender: TObject);
var
  create_sql, insert_sql, truncate_sql, select_sql, select_sql2, kodes, nades: String;
begin
  with cxGrid1DBTableView1.DataController do
  begin
    BeginUpdate;
    try
      while RecordCount > 0 do
        DeleteRecord(0);
    finally
      EndUpdate;
    end;
    RecordCount:=0;
  end;
  
  //cek kode kecamatan
  if(skec = '') then
    showmessage('pilih kecamatan terlebih dahulu')
  else begin
    //showmessage('masuk');
    threadGanda.threadDialog:=threadDialogGanda;
    threadGanda.Execute(Self);
  end;
end;

procedure TForm_NView.threadGandaExecute(Sender: TObject; Params: Pointer);
var
  create_sql, insert_sql, truncate_sql, select_sql, select_sql2, kodes, nades: String;
begin
    //cxGrid1DBTableView1.BeginUpdate;
    cxGrid1DBTableView1.DataController.Filter.Clear;
    //cxGrid1DBTableView1.DataController.DataSource;
    cxGrid1DBTableView1.ClearItems;
    //cxGrid1DBTableView1.EndUpdate;

    //drop tabel
    truncate_sql:='DROP TABLE IF EXISTS record_ganda';
    qryOnce.Active:=false;
    qryOnce.SQL.Clear;
    qryOnce.SQL.Text:=truncate_sql;
    qryOnce.ExecSQL;

    //buat tabel
    create_sql:='CREATE TABLE IF NOT EXISTS `record_ganda` ('
      +'`ID_USER` INT NOT NULL ,'
      +'`NIK` CHAR( 36 ) NOT NULL ,'
      +'`NKK` CHAR( 36 ) NOT NULL , '
      +'`NAMA` CHAR( 60 ) NOT NULL ,'
      +'`TEMPAT_LAHIR` CHAR( 60 ) NOT NULL ,'
      +'`TANGGAL_LAHIR` CHAR( 10 ) NOT NULL ,'
      +'`IBU` CHAR( 60 ) NOT NULL ,'
      +'`STATUS_PERKAWINAN` CHAR( 1 ) NOT NULL ,'
      +'`JENIS_KELAMIN` CHAR( 1 ) NOT NULL ,'
      +'`ALAMAT` CHAR( 150 ) NOT NULL ,'
      +'`RW` CHAR( 3 ) NOT NULL ,'
      +'`RT` CHAR( 3 ) NOT NULL ,'
      +'`DUSUN` CHAR( 30 ) NOT NULL ,'
      +'`DI_TPS` CHAR( 3 ) NOT NULL ,'
      +'`GANDA` CHAR( 1 ) NOT NULL ,'
      +'`NAMA_DESA` CHAR( 40 ) NOT NULL ,'
      +'`TABEL` CHAR( 20 ) NOT NULL'
      +') ENGINE = MyISAM;';
    qryOnce.Active:=false;
    qryOnce.SQL.Clear;
    qryOnce.SQL.Text:=create_sql;
    qryOnce.ExecSQL;

    //cari desa
    select_sql:='SELECT KODE_DESA, TAMPIL FROM desa WHERE KODE_KECAMATAN = '+quotedStr(skec);
    qrySelect.Active:=false;
    qrySelect.SQL.Clear;
    qrySelect.SQL.Text:=select_sql;
    qrySelect.Active:=true;
    qrySelect.First;
    while(not qrySelect.Eof) do begin
      kodes:=qrySelect.fieldByName('KODE_DESA').AsString;
      nades:=qrySelect.fieldByName('TAMPIL').AsString;
      select_sql:='SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '+quotedStr('pemilih_'+kodes)+' AND TABLE_SCHEMA = '+quotedStr(zConnection1.Database);

      qrySelect2.Active:=false;
      qrySelect2.SQL.Clear;
      qrySelect2.SQL.Text:=select_sql;
      qrySelect2.Active:=true;

      if(qrySelect2.RecordCount > 0) then begin
        insert_sql:='INSERT INTO record_ganda '
            +'SELECT a.ID_USER, a.NIK, a.NKK, a.NAMA, a.TEMPAT AS `TEMPAT_LAHIR`, a.TANGGAL AS `TANGGAL_LAHIR`, a.IBU, a.KAWIN AS `STATUS_PERKAWINAN`, a.KELAMIN AS `JENIS_KELAMIN`, a.ALAMAT, a.RW, a.RT, a.DUSUN, b.NAMA AS `DI_TPS`, a.GANDA, '+quotedStr(nades)+', '+quotedStr('pemilih_'+kodes)+' FROM pemilih_'+kodes+' a LEFT JOIN'+' daftar_tps b ON a.TPS = b.ID_TPS WHERE a.STATUS2="0" AND a.GANDA="1" ORDER BY a.RW,a.RT,a.NKK ASC';
        qryOnce.Active:=false;
        qryOnce.SQL.Clear;
        qryOnce.SQL.Text:=insert_sql;
        qryOnce.ExecSQL;
      end;
      qrySelect.Next;
    end;

    create_sql := 'ALTER TABLE `record_ganda` ADD UNIQUE ('
      +'`ID_USER` ,'
      +'`TABEL`'
      +')';
    qryOnce.Active:=false;
    qryOnce.SQL.Clear;
    qryOnce.SQL.Text:=create_sql;
    qryOnce.ExecSQL;

    //kita tampilkan ke tabel
    qrySelect3.Active:=false;
    qrySelect3.SQL.Clear;
    qrySelect3.SQL.Text:='SELECT * FROM record_ganda';
    qrySelect3.Active:=true;

    btnMerah.Enabled:=true;
end;

procedure TForm_NView.btnMerahClick(Sender: TObject);
var
  buttonSelected,idx:integer;
  iduser,tabeluser:string;
begin
  if(cxGrid1DBTableView1.Controller.SelectedRowCount=0) then
    showmessage('pilih data terlebih dahulu')
  else begin
    buttonSelected := MessageDlg('Apakah anda yakin pemilih yang dipilih bukan data ganda?',mtConfirmation , mbOKCancel, 0);
    if buttonSelected = mrOK  then begin
       //ubah_merah.Free;
       //ubah_merah_tabel.Free;
       ubah_merah := Tstringlist.Create;
       ubah_merah_tabel := Tstringlist.Create;
       with cxGrid1DBTableView1.Controller do begin
        for idx:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[idx].Values[0];
          ubah_merah.Add(iduser);
          if(sdesa = '') then
            tabeluser:=SelectedRows[idx].Values[16]
          else
            tabeluser := 'pemilih_'+sdesa;
          ubah_merah_tabel.Add(tabeluser);
        end;
       end;
      ThreadUbahMerah.ThreadDialog:=ThreadDialogUbahMerah;
      ThreadUbahMerah.Execute(Self);
    end;
  end;
end;

procedure TForm_NView.threadUbahMerahExecute(Sender: TObject;
  Params: Pointer);
var
  idx:integer;
  id_pemilih, tabel_pemilih, query, iQue, idtgl, idtbl:string;
begin
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'INSERT INTO tanggal (TANGGAL) VALUES ("'+tanggal+'")';
    ExecSQL;
  end;
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'SELECT * FROM tanggal ORDER BY ID_TANGGAL DESC';
    Active:=True;
    idtgl := FieldByName('ID_TANGGAL').AsString;  //dapat ID_TGL
  end;
  for idx:=0 to ubah_merah.Count-1 do begin
        id_pemilih:=ubah_merah[idx];
        tabel_pemilih:=ubah_merah_tabel[idx];
        with ZQuery1 do begin //cari id tabel
          query:='SELECT ID FROM penyimpan WHERE NAMA = '+quotedStr(tabel_pemilih);
          active:=false;
          sql.Clear;
          sql.text:=query;
          active:=true;
          idtbl := FieldByName('ID').AsString;  //dapat ID_TGL
        end;
        with ZQuery1 do begin
          active:=false;
          sql.Clear;
          query:='SELECT * FROM '+tabel_pemilih+' WHERE ID_USER='+id_pemilih;
  //      ShowMessage(query);
          sql.Text:=query;
          Active:=true;
          first;
          iQue:='INSERT INTO `history` (ID_USER, `NIK`, `NKK`, `NAMA`, `TEMPAT`, `TANGGAL`, '+
          '`IBU`, `AGAMA`, `KAWIN`, `KELAMIN`, `KELAINAN`, `ALAMAT`, `RW`, `RT`, `DUSUN`, `KET`, '+
          '`ID_TANGGAL`, TPS, STATUS1, STATUS2, GANDA, STATUS3, STATUSP, ALASANP'+
          ',CACAT,PENDIDIKAN,PEKERJAAN,STATUSR,WN,USERNAME,KET_AKSI) VALUES '+
          '('+QuotedStr(idtbl+'-'+FieldByName('ID_USER').AsString)+
          ','+QuotedStr(HandleSpec(FieldByName('NIK').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('NKK').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('NAMA').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('TEMPAT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('TANGGAL').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('IBU').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('AGAMA').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KAWIN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KELAMIN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KELAINAN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('ALAMAT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('RW').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('RT').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('DUSUN').AsString))+
          ','+QuotedStr(HandleSpec(FieldByName('KET').AsString))+
          ','+FieldByName('ID_TANGGAL').AsString+
          ','+FieldByName('TPS').AsString+
          ','+QuotedStr(FieldByName('STATUS1').AsString)+
          ','+QuotedStr(FieldByName('STATUS2').AsString)+
          ','+QuotedStr(FieldByName('GANDA').AsString)+
          ','+QuotedStr(FieldByName('STATUS3').AsString)+
          ','+QuotedStr(FieldByName('STATUSP').AsString)+
          ','+QuotedStr(FieldByName('ALASANP').AsString)+
          ','+QuotedStr(FieldByName('CACAT').AsString)+
          ','+QuotedStr(FieldByName('PENDIDIKAN').AsString)+
          ','+QuotedStr(FieldByName('PEKERJAAN').AsString)+
          ','+QuotedStr(FieldByName('STATUSR').AsString)+
          ','+QuotedStr(FieldByName('WN').AsString)+
          ','+QuotedStr(username)+
          ','+QuotedStr('0')+
          ')';
          //
          active:=false;
          sql.Clear;
  //        ShowMessage(ique);
          sql.Text:=ique;
          ExecSQL;
          //
          active:=false;
          sql.Clear;

          query:='UPDATE '+tabel_pemilih+' SET GANDA="0", KET = "", ID_TANGGAL = "'+idtgl+'" WHERE ID_USER='+id_pemilih;
        //ShowMessage(query);
          sql.Text:=query;
          ExecSQL;
        end;
      end;
      ubah_merah.Free;
      ubah_merah_tabel.Free;
end;

procedure TForm_NView.threadUbahMerahFinishAll(Sender: TObject);
begin
  ShowMessage('Data telah diubah');
  //threadGanda.threadDialog:=threadDialogGanda;
  //threadGanda.Execute(Self);
end;

procedure TForm_NView.threadGandaFinishAll(Sender: TObject);
begin
    cxGrid1DBTableView1.BeginUpdate;
    cxGrid1DBTableView1.DataController.DataSource:=dsGanda;
    cxGrid1DBTableView1.DataController.CreateAllItems;
    cxGrid1DBTableView1.Columns[0].Width:=40;
    cxGrid1DBTableView1.Columns[1].Width:=105;
    cxGrid1DBTableView1.Columns[2].Width:=105;
    cxGrid1DBTableView1.Columns[3].Width:=120;
    cxGrid1DBTableView1.Columns[4].Width:=90;
    cxGrid1DBTableView1.Columns[6].Width:=120;
    cxGrid1DBTableView1.Columns[9].Width:=150;
    cxGrid1DBTableView1.Columns[12].Width:=150;
    cxGrid1DBTableView1.Columns[14].Width:=50;
    cxGrid1DBTableView1.Columns[15].Width:=150;
    cxGrid1DBTableView1.Columns[16].Visible:=false;
    cxGrid1DBTableView1.EndUpdate;

    lblket.Caption:=inttostr(qrySelect3.recordCount)+' orang';
    lblketmerah.Caption:='';
end;

procedure TForm_NView.btnRTRWClick(Sender: TObject);
var
  i:integer;
  iduser:string;
  pemilihs:tstringlist;
  fR: TFrmRTRW;
begin
  //ambil id
  if (cxGrid1DBTableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilihs := Tstringlist.Create;
    with cxGrid1DBTableView1.Controller do begin
        for i:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[i].Values[0];
          pemilihs.Add(iduser);
        end;
    end;
    fR := TFrmRTRW.Create(Application,ptable,pid,true,tid,1,pemilihs,username);
    //showmessage('hoi');
  end
  else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
end;

procedure TForm_NView.btnPermanenClick(Sender: TObject);
var
  query,ique,itabel,id_pemilih,iduser:String;
  buttonSelected, idx : Integer;
  pemilihs : tstringList;
begin
  //ambil yg diselect
  if (cxGrid2DBTableView1.Controller.SelectedRowCount>0) and (sdesa<>'') then begin
    pemilih_kembali := Tstringlist.Create;
    with cxGrid2DBTableView1.Controller do begin
        for idx:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[idx].Values[0];
          pemilih_kembali.Add(iduser);
        end;
    end;
    buttonSelected := MessageDlg('Apakah anda yakin akan menghapus secara permanen data ini? Data yang telah dihapus tidak akan bisa dikembalikan lagi',mtConfirmation , mbOKCancel, 0);
    if buttonSelected = mrOK  then begin
      ThreadPermanen.ThreadDialog:=ThreadDialogKembali;
      ThreadPermanen.Execute(Self);
    end;
  end
    else
  begin
    if (sdesa='') then
      showmessage('Pilih desa/kelurahan terlebih dahulu')
    else
      showmessage('Pilih pemilih terlebih dahulu');
  end;
end;

procedure TForm_NView.threadPermanenFinishAll(Sender: TObject);
begin
  ShowMessage('Data telah dikembalikan');
end;

procedure TForm_NView.threadPermanenExecute(Sender: TObject;
  Params: Pointer);
var
  idx:integer;
  id_pemilih, query, iQue, idtgl, tabel:string;
begin
  tabel:=getIdSimpan('pemilih_'+sdesa);
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'INSERT INTO tanggal (TANGGAL) VALUES ("'+tanggal+'")';
    ExecSQL;
  end;
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'SELECT * FROM tanggal ORDER BY ID_TANGGAL DESC';
    Active:=True;
    idtgl := FieldByName('ID_TANGGAL').AsString;  //dapat ID_TGL
  end;
  for idx:=0 to pemilih_kembali.Count-1 do begin
        id_pemilih:=pemilih_kembali[idx];
        with ZQuery1 do begin
          active:=false;
          sql.Clear;
          query:='DELETE FROM history WHERE ID_USER='+quotedSTR(tabel+'-'+id_pemilih);
          //showmessage(query);

          sql.Text:=query;
          ExecSQL;
          //
          active:=false;
          sql.Clear;

          query:='DELETE FROM pemilih_'+sdesa+' WHERE ID_USER='+id_pemilih;
        //ShowMessage(query);
          sql.Text:=query;
          ExecSQL;
        end;
      end;

end;

procedure TForm_NView.btnCacatClick(Sender: TObject);
var
  buttonSelected,idx:integer;
  iduser,tabeluser:string;
begin
  if(cxGrid1DBTableView1.Controller.SelectedRowCount=0) then
    showmessage('pilih data terlebih dahulu')
  else begin
    buttonSelected := MessageDlg('Apakah anda yakin menghilangkan tanda cacat?',mtConfirmation , mbOKCancel, 0);
    if buttonSelected = mrOK  then begin
       //ubah_merah.Free;
       //ubah_merah_tabel.Free;
       ubah_cacat := Tstringlist.Create;
       ubah_cacat_tabel := Tstringlist.Create;
       with cxGrid1DBTableView1.Controller do begin
        for idx:=0 to SelectedRowCount-1 do begin
          iduser:=SelectedRows[idx].Values[0];
          ubah_cacat.Add(iduser);
          if(sdesa = '') then
            tabeluser:=SelectedRows[idx].Values[16]
          else
            tabeluser := 'pemilih_'+sdesa;
          ubah_cacat_tabel.Add(tabeluser);
        end;
       end;
      ThreadCacat.ThreadDialog:=ThreadDialogCacat;
      ThreadCacat.Execute(Self);
    end;
  end;
end;

procedure TForm_NView.threadCacatFinishAll(Sender: TObject);
begin
  ShowMessage('Data telah diubah');
end;

procedure TForm_NView.threadCacatExecute(Sender: TObject; Params: Pointer);
var
  idx:integer;
  id_pemilih, tabel_pemilih, query, iQue, idtgl, idtbl:string;
begin
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'INSERT INTO tanggal (TANGGAL) VALUES ("'+tanggal+'")';
    ExecSQL;
  end;
  with ZQuery1 do  //masukkin nih gan
  begin
    Active:=False;
    sql.Clear;
    sql.Text := 'SELECT * FROM tanggal ORDER BY ID_TANGGAL DESC';
    Active:=True;
    idtgl := FieldByName('ID_TANGGAL').AsString;  //dapat ID_TGL
  end;
  for idx:=0 to ubah_cacat.Count-1 do begin
        id_pemilih:=ubah_cacat[idx];
        tabel_pemilih:=ubah_cacat_tabel[idx];
        with ZQuery1 do begin //cari id tabel
          query:='SELECT ID FROM penyimpan WHERE NAMA = '+quotedStr(tabel_pemilih);
          active:=false;
          sql.Clear;
          sql.text:=query;
          active:=true;
          idtbl := FieldByName('ID').AsString;  //dapat ID_TGL
        end;
        with ZQuery1 do begin
          active:=false;
          sql.Clear;
          query:='SELECT * FROM '+tabel_pemilih+' WHERE ID_USER='+id_pemilih;
  //      ShowMessage(query);
          sql.Text:=query;
          Active:=true;
          first;

          query:='UPDATE '+tabel_pemilih+' SET CACAT="0", KET = "", ID_TANGGAL = "'+idtgl+'" WHERE ID_USER='+id_pemilih;
        //ShowMessage(query);
          sql.Text:=query;
          ExecSQL;
        end;
      end;
      ubah_cacat.Free;
      ubah_cacat_tabel.Free;
end;

end.
